# -*- coding: utf-8 -*-

# Songwrite 2
# Copyright (C) 2001-2007 Jean-Baptiste LAMY -- jibalamy@free.fr
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import sys
import qt
import editobj2
if editobj2.GUI == "Qt":
  app = qt.QApplication(sys.argv)
else:
  try:
    import qtpe
    app = qtpe.QPEApplication(["Songwrite2"])
  except ImportError:
    app = qt.QApplication(["Songwrite2"])

mainloop = app.exec_loop

from songwrite2.main import *
from songwrite2.canvas_qt import Canvas


class App(BaseApp):
  def menu_image(self, filename):
    pixmap = qt.QPixmap(os.path.join(globdef.DATADIR, filename), "png")
    image  = pixmap.convertToImage()
    pixmap = qt.QPixmap(32, 32)
    pixmap.convertFromImage(image.smoothScale(32, 32))
    return qt.QIconSet(pixmap)
  
  def append_to_menu(self, menu, has_submenu, label, command = None, arg = None, accel = "", image = None):
    if arg:
      command2 = lambda index: command(index, arg)
      self.lambdas.append(command2)
    else:
      command2 = command
      
    if has_submenu:
      menu_item = qt.QPopupMenu(self.q)
      if command2:
        index = menu.insertItem(_(label), menu_item)
        menu.connectItem(index, command2)
      else:
        index = menu.insertItem(_(label), menu_item)
        
    else:
      menu_item = None
      if image:
        if command2: index = menu.insertItem(image, _(label), command2)
        else:        index = menu.insertItem(image, _(label))
      else:
        if command2: index = menu.insertItem(_(label), command2)
        else:        index = menu.insertItem(_(label))
        
    if accel:
      menu.setAccel(qt.QAccel.stringToKey(accel.replace("-", "+").replace("C", "Ctrl")), index)
      
    return menu_item
  
  def append_separator_to_menu(self, menu):
    menu.insertSeparator()
    
  def create_menubar(self):
    return self.q.menuBar()
  
  def __init__(self, song = None):
    self.q = qt.QMainWindow()
    
    self.lambdas = []
    
    self.vbox = qt.QVBox(self.q)
    self.q.setCentralWidget(self.vbox)
    
    BaseApp.__init__(self, song)
    
    zoom_levels = [0.25, 0.35, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 4.0]
    
    def set_zoom(menu_item, zoom):
      self.canvas.set_zoom(zoom)
    self.on_set_zoom = set_zoom
    
    zoom_menu  = self.append_to_menu(self.menubar, 1, u"100%")
    self.zoom_menu_index = self.menubar.count() - 1
    for zoom in zoom_levels:
      self.append_to_menu(zoom_menu, 0, u"%s%%" % int(zoom * 100.0), self.on_set_zoom, arg = zoom)

    if editobj2.GUI == "Qt":
      self.q.showMaximized()
    else:
      app.showMainWidget(self.q)
    observe(globdef.config, self.config_listener)
    
    self.q.closeEvent = self.closeEvent

    self.destroy = self.q.destroy
    
  def config_listener(self, obj, type, new, old):
    if type is object:
      if new["SIDE_BAR_POSITION"] != old["SIDE_BAR_POSITION"]: self.create_content()
    
  def create_content(self):
    self.canvas = Canvas(self, self.song, self.vbox)
    
  def set_song(self, song):
    BaseApp.set_song(self, song)
    
    self.q.setCaption(u"Songwrite2 -- %s" % song.title)

    if getattr(self, "canvas", None):
      zoom = self.canvas.zoom
      self.canvas.hide()
      try:
        self.vbox.layout().remove(self.canvas)
      except: pass # QTopia do not have it
      self.vbox.removeChild(self.canvas)
      self.canvas.destroy()
      
      #self.canvas.destroy()
      self.canvas = Canvas(self, self.song, self.vbox, zoom)
      self.canvas.show()
      
  def set_menu_enable(self, menu, enable): menu.set_sensitive(enable)
  def set_menu_label (self, menu, label ): menu.get_child().set_text(label)
  
  def prompt_open_filename(self, filter = None, title = None):
    l = []
    def on_validate(filename): l.append(filename)
    
    import editobj2.qtopia_file_chooser
    print globdef.config.LAST_DIR
    editobj2.qtopia_file_chooser.ask_filename(on_validate, globdef.config.LAST_DIR + "/")
    if l: return l[0]
    
  def prompt_save_filename(self, filter = None, title = None):
    return self.prompt_open_filename()
  
  def on_open(self, event = None):
    if self.check_save(): return
    
    filename = self.prompt_open_filename()
    if not filename: return
    self.open_filename(filename, do_check_save = 0) # check_save has already been done before asking the filename
    
  def check_save(self):
    if not self.song: return 0
    
    if self.undo_stack.undoables != self.last_undoables:
      # The undoable actions have changed => the song need to be saved.
      
      l = []
      def on_validate(o): l.append(o)
      
      self.edit(_(u"Modifications have not been saved. Quit anyway?"), on_validate)

      if l[0]: return 0
      return 1
    
    else: return 0
    
  def closeEvent(self, e):
    if self.check_save(): return
    
    e.accept()
    
    del APPS[self.song]
    if self.songbook: del APPS[self.songbook]
    self.destroy()
    
    if len(APPS) == 0:
      globdef.config.save()
      sys.exit()
      
    
# class EditNotebook(object):
#   def __init__(self, undo_stack, tab_pos):
#     self.tab_pos = tab_pos
#     if tab_pos in "top":
#       self.box     = qt.QVBox()
#       self.tab_box = qt.QHBox(self.box)
#     else:
#       self.box     = qt.QHBox()
#       self.tab_box = qt.QVBox(self.box)
#     self.tab_box.setMargin(5)
#     self.widget_stack = qt.QWidgetStack(self.box)
    
#     self.undo_stack      = undo_stack
#     self.current         = 0
#     self.tab_width       = 0
#     self.objs            = []
#     self.tabs            = []
#     self.icon_panes      = []
#     self.attribute_panes = []
#     self.extra_widgets   = []
    
#   def delete_tab(self, i):
#     self.remove_page(i)
#     del self.objs           [i]
#     del self.icon_panes     [i]
#     del self.attribute_panes[i]
#     del self.extra_widgets  [i]
    
#   def add_tab(self, obj = None, widget = None, widget_extend = 1):
#     self.insert_tab(len(self.objs), obj, widget, widget_extend)
    
#   def insert_tab(self, i, obj = None, widget = None, widget_extend = 1):
#     if widget:
#       if self.tab_pos in "left": page = qt.QHBox(self.widget_stack)
#       else:                      page = qt.QVBox(self.widget_stack)
#       scroll = qt.QScrollView(page)
#       widget.reparent(page, qt.QPoint())
#       self.widget_stack.addWidget(page, i)
#     else:
#       scroll = qt.QScrollView(self.widget_stack)
#       self.widget_stack.addWidget(scroll, i)
      
#     scroll.setResizePolicy(qt.QScrollView.AutoOneFit)
#     scroll.setHScrollBarMode(qt.QScrollView.AlwaysOff)
    
#     tab = qt.QHBox(self.tab_box)
#     tab.mousePressEvent = lambda arg: self.set_current_page(i)
#     icon_pane      = editor.IconPane     ("Qt", tab, 1, 1, 0)
#     attribute_pane = editor.AttributePane("Qt", scroll.viewport(), None, self.undo_stack)
#     scroll.addChild(attribute_pane)
    
#     self.objs           .insert(i, None)
#     self.tabs           .insert(i, tab)
#     self.icon_panes     .insert(i, icon_pane)
#     self.attribute_panes.insert(i, attribute_pane)
#     self.extra_widgets  .insert(i, widget)
    
#     if obj: self.edit(i, obj)
    
#     if (i <= self.current) and (self.current < len(self.objs) - 1): self.current += 1
    
#   def edit(self, i, obj, force = 0):
#     if i < 0: i = len(self.objs) + i
    
#     if not self.objs[i] is obj:
#       self.objs[i] = obj
#       self.icon_panes[i].edit(obj)
#       if self.extra_widgets[i]: self.extra_widgets[i].edit(obj)
      
#       #self.icon_pane_changed(self.icon_panes[i])
#       if (i == self.current) or force:
#         self.attribute_panes[i].edit(obj)
#       if (i == len(self.objs) - 2): self.check_mesures()
      
      
#   def check_mesures(self):
#     if isinstance(self.objs[-2], introsp.ObjectPack):
#       numbers = [m.get_number() for m in self.objs[-2].objects]
#       if numbers:
#         label = _(u"Bars #%s to #%s") % (min(numbers) + 1, max(numbers) + 1)
#         if self.current == len(self.objs) - 2: label = u"<b>%s</b>" % label
#         self.icon_panes[-2].label.set_markup(label)
        
#   def on_switch_page(self, notebook, page, i):
#     self.icon_pane_changed(self.icon_panes[self.current])
#     self.icon_panes[self.current].config(1, 1, 0)
#     self.icon_panes[i           ].config(0, 1, 1)
#     self.icon_pane_changed(self.icon_panes[self.current])
#     old_current = self.current
#     self.current = i
#     if (self.current == len(self.objs) - 2) or (old_current == len(self.objs) - 2): self.check_mesures()
#     self.attribute_panes[i].edit(self.objs[i])
#     self.attribute_panes[i].queue_resize()
#     self.icon_panes[i].show_all()
#     self.icon_pane_changed(self.icon_panes[i])
    
#   def icon_pane_changed(self, icon_pane):
#     if self.get_tab_pos() in (gtk.POS_LEFT, gtk.POS_RIGHT):
#       icon_pane.set_size_request(-1, -1)
#       tab_width = icon_pane.size_request()[0]
#       if tab_width > self.tab_width: self.tab_width = tab_width
#       for icon_pane in self.icon_panes: icon_pane.set_size_request(self.tab_width, -1)
#     else:
#       try:
#         icon_pane.label.set_property("visible", 0)
#         icon_pane.image.set_alignment(0.5, 0.5)
#       except: pass

#   def set_current_page(self, i):
#     if i < 0: i = i + len(self.objs)
#     self.icon_panes[self.current].config(1, 1, 0)
#     self.icon_panes[i           ].config(0, 1, 1)
    
#     old_current = self.current
#     self.current = i
#     self.widget_stack.raiseWidget(i)
#     #if (self.current == len(self.objs) - 2) or (old_current == len(self.objs) - 2): self.check_mesures()
    
    
# class PlaylistPane(qt.QHBox):
#   def __init__(self, parent, main, undo_stack = None):
#     qt.QHBox.__init__(self, parent.q)
    
#     self.main           = main
    
#     scroll = qt.QScrollView(self)
#     scroll.setHScrollBarMode(qt.QScrollView.AlwaysOff)
#     scroll.setResizePolicy(qt.QScrollView.AutoOneFit)
#     scroll.setFrameShape(qt.QFrame.NoFrame)
#     #self.setMargin(5)
    
#     self.hierarchy_pane = editor.HierarchyPane("Qt", scroll.viewport(), lambda o: None, undo_stack)
#     self.childhood_pane = editor.ChildhoodPane("Qt", self             ,                 undo_stack)
#     scroll.addChild(self.hierarchy_pane)
    
#     self.hierarchy_pane.set_childhood_pane(self.childhood_pane)
    
#   def set_playlist(self, playlist):
#     self.hierarchy_pane.edit(playlist)
    
#   def edit(self, o): pass


# class PartitionsPane(qt.QHBox):
#   def __init__(self, parent, main, undo_stack = None):
#     qt.QHBox.__init__(self, parent.q)
    
#     self.main           = main
#     self.childhood_pane = editor.ChildhoodPane("Qt", self, undo_stack)
    
#     self.setMargin(5)
    
#   def edit(self, partition):
#     self.childhood_pane.edit(partition.song, partition)
