#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""X Tile module"""

#      x-tile.py
#      
#      Copyright 2009-2010
#      Giuseppe Penone <giuspen@gmail.com>,
#      Chris Camacho (chris_c) <chris_camacho@yahoo.com>.
#      
#      plus many thanks to  http://tronche.com/gui/x/xlib/
#                      and  http://tripie.sweb.cz/utils/wmctrl/
#
#      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 2 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, write to the Free Software
#      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#      MA 02110-1301, USA.

import gtk, sys, os, subprocess, gettext
import gnomeapplet, gobject, gconf
import __builtin__


# language installation
gconf_client = gconf.client_get_default()
gconf_client.add_dir("/apps/x-tile", gconf.CLIENT_PRELOAD_NONE)
lang_str = gconf_client.get_string("/apps/x-tile/language")
if lang_str == None:
   gconf_client.set_string("/apps/x-tile/language", "default")
   lang_str = "default"
if lang_str != "default": os.environ["LANGUAGE"] = lang_str
try: gettext.translation(cons.APP_NAME, cons.LOCALE_PATH).install()
except:
   def _(transl_str):
      return transl_str
   __builtin__._ = _

if os.path.isdir('modules'): MODULES_PATH = 'modules/'
else: MODULES_PATH = '/usr/share/x-tile/modules/'
sys.path.append(MODULES_PATH)
import cons, globs, core

__builtin__.glob = globs.GlobalsObject()

# icons generation
factory = gtk.IconFactory()
for filename, stock_name in cons.ICONS_FILENAMES:
   pixbuf = gtk.gdk.pixbuf_new_from_file(filename)
   iconset = gtk.IconSet(pixbuf)
   factory.add(stock_name, iconset)
factory.add_default()


class XTileApplet(gnomeapplet.Applet):
   """The application's Appletizator class"""
   
   def __init__(self, applet, iid):
      """Initializes the Applet, connects the events to the callback functions"""
      self.__gobject_init__()
      self.applet = applet
      size = self.applet.get_size() - 2
      pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(cons.ICON_PLACE, size, size)
      self.image = gtk.Image()
      self.image.set_from_pixbuf(pixbuf)
      self.applet.add(self.image)
      self.applet.connect("button-press-event", self.on_button_press)
      self.applet.connect("change-size", self.reload_image)
      self.applet.connect("destroy-event", self.cleanup)
      self.applet.connect("delete-event", self.cleanup)
      self.applet.set_tooltip_text(cons.APPLET_DESC)
      self.applet.show_all()
      glob.alive = False
      
   def cleanup(self, *args):
      """Deletes the Applet"""
      del self.applet
      
   def reload_image(self, *args):
      """Reloads the bar icon"""
      size = self.applet.get_size() - 2
      pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(cons.ICON_PLACE, size, size)
      self.image.set_from_pixbuf(pixbuf)
   
   def on_button_press(self, widget, event):
      """When the user clicks upon the Applet..."""
      if (event.type == gtk.gdk.BUTTON_PRESS):
         if (event.button == 1):
            if glob.alive:
               glob.alive = False
               self.gui.quit_application()
            else:
               glob.alive = True
               self.gui = core.XTile(core.InfoModel())
               self.gui.launch_application()
               self.gui.reload_windows_list()
         elif (event.button == 3): self.show_applet_menu()

   def show_applet_menu(self):
      """Opens the applet menu (on gnome bar)"""
      self.applet.setup_menu(cons.APPLET_MENU_XML, cons.get_applet_menu_verbs(self), None)
      
   def hide_and_process(self, command_str):
      """Hide the X Tile Window if Visible, the Process the Command"""
      if glob.alive:
         glob.alive = False
         self.gui.quit_application()
      subprocess.call(command_str, shell=True)
      
   def tile_all_vertically(self, *args):
      """Just tile Vertically all opened windows"""
      self.hide_and_process("x-tile --tile-all-vertically &")

   def tile_all_horizontally(self, *args):
      """Just tile Horizontally all opened windows"""
      self.hide_and_process("x-tile --tile-all-horizontally &")
      
   def tile_all_triangle_up(self, *args):
      """Just tile Triangle Up all opened windows"""
      self.hide_and_process("x-tile --tile-all-triangle-up &")
      
   def tile_all_triangle_down(self, *args):
      """Just tile Triangle Down all opened windows"""
      self.hide_and_process("x-tile --tile-all-triangle-down &")
      
   def tile_all_triangle_left(self, *args):
      """Just tile Triangle Left all opened windows"""
      self.hide_and_process("x-tile --tile-all-triangle-left &")
      
   def tile_all_triangle_right(self, *args):
      """Just tile Triangle Right all opened windows"""
      self.hide_and_process("x-tile --tile-all-triangle-right &")
      
   def tile_all_quad(self, *args):
      """Just tile Quad all opened windows"""
      self.hide_and_process("x-tile --tile-all-quad &")
   
   def maximize_all(self, *args):
      """Maximize all opened windows"""
      self.hide_and_process("x-tile --maximize-all &")
      
   def dialog_about(self, *args):
      """Show the About Dialog and hide it when a button is pressed"""
      glade = core.GladeWidgetsWrapper(cons.GLADE_PATH + 'x-tile.glade', self)
      glade.aboutdialog.set_version(cons.VERSION)
      glade.aboutdialog.run()
      glade.aboutdialog.destroy()
      glade = None

# appletization part
gobject.type_register(XTileApplet)

def x_tile_applet_factory(applet, iid):
   """Calls The Appletization Class"""
   XTileApplet(applet, iid)
   return gtk.TRUE

if len(sys.argv) > 1:
   arg = sys.argv[1]
   if arg == "--without-panel":
      # x-tile runs independently from any panel
      x=core.XTile(core.InfoModel())
      x.launch_application()
      x.reload_windows_list()
      gtk.main()
      sys.exit(0)
   elif arg == "--run-in-window":
      # the applet is reproduced in a little window
      main_window = gtk.Window(gtk.WINDOW_TOPLEVEL)
      main_window.set_title("X Tile Applet")
      main_window.connect("destroy", gtk.main_quit)
      main_window.set_default_size(36, 36)
      app = gnomeapplet.Applet()
      x_tile_applet_factory(app, None)
      app.reparent(main_window)
      main_window.show_all()
      gtk.main()
      sys.exit(0)
   elif arg == "--help":
      print cons.HELP_TEXT
      sys.exit(0)
   elif arg in ["--tile-all-vertically", "--tile-all-horizontally",
                "--tile-all-triangle-up", "--tile-all-triangle-down",
                "--tile-all-triangle-left", "--tile-all-triangle-right",
                "--tile-all-quad", "--maximize-all"]:
      x=core.XTile(core.InfoModel())
      x.launch_application()
      x.reload_windows_list()
      x.flag_all_rows()
      if arg == "--tile-all-vertically": x.tile_vertically()
      elif arg == "--tile-all-horizontally": x.tile_horizontally()
      elif arg == "--tile-all-triangle-up": x.tile_triangle_up()
      elif arg == "--tile-all-triangle-down": x.tile_triangle_down()
      elif arg == "--tile-all-triangle-left": x.tile_triangle_left()
      elif arg == "--tile-all-triangle-right": x.tile_triangle_right()
      elif arg == "--tile-all-quad": x.tile_quad()
      elif arg == "--maximize-all": x.maximize_checked_windows()
      sys.exit(0)


def main():
   """Calls the gnomeapplet bonobo_factory function"""
   gnomeapplet.bonobo_factory("OAFIID:GNOME_X_Tile_Applet_Factory",
                              XTileApplet.__gtype__,
                              "X Tile Gnome Applet", "1.0",
                              x_tile_applet_factory)

if __name__ == "__main__": main()
