guyzmo / pida-bugfixing (http://pida.co.uk/)

fork of pida-main

all my bugfixeso

Clone this repository (size: 3.2 MB): HTTPS / SSH
$ hg clone http://bitbucket.org/guyzmo/pida-bugfixing/
commit 1684: fe32034b57cc
parent 1683: 4059537c20ef
branch: default
tags: tip
fixing Ticket #261. Changed sorting order and names, but not made it alphabetical.
guyzmo
16 months ago
r1684:fe32034b57cc 981 loc 32.3 KB embed / history / annotate / raw /
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
# -*- coding: utf-8 -*-
"""
    :copyright: 2005-2008 by The PIDA Project
    :license: GPL 2 or later (see README/COPYING/LICENSE)
"""

import gtk

from os import listdir, path

import os
import shutil

import cgi

import re

# PIDA Imports
from pida.core.service import Service
from pida.core.features import FeaturesConfig
from pida.core.pdbus import DbusConfig, EXPORT
from pida.core.commands import CommandsConfig
from pida.core.events import EventsConfig
from pida.core.actions import ActionsConfig
from pida.core.actions import TYPE_NORMAL, TYPE_MENUTOOL, TYPE_DROPDOWNMENUTOOL, TYPE_RADIO, TYPE_TOGGLE
from pida.core.options import OptionsConfig
from pida.core.environment import get_uidef_path
from pida.core.log import get_logger

from pida.utils.gthreads import GeneratorTask, AsyncTask
from pida.utils.path import homedir

from pida.ui.views import PidaView
from pida.ui.objectlist import AttrSortCombo
from pida.ui.dropdownmenutoolbutton import DropDownMenuToolButton
from pida.ui.gtkforms import DialogOptions, create_gtk_dialog
from kiwi.ui.objectlist import Column, ColoredColumn, ObjectList

import filehiddencheck

# locale
from pida.core.locale import Locale
locale = Locale('filemanager')
_ = locale.gettext

IEXPORT = EXPORT(suffix='filemanager')

state_text = dict(
        hidden=' ',
        none='?',
        new='A', #XXX
        added='A',
        modified='M',
        ignored=' ',
        normal=' ',
        error='E',
        empty='!',
        conflict='C',
        removed='D',
        missing='!',
        max='+',
        external='>',
        )

state_style = dict( # tuples of (color, is_bold, is_italic)
        unknown=('pida-fm-unknown', False, False),
        hidden=('pida-fm-hidden', False, True),
        ignored=('pida-fm-ignored', False, True),
        #TODO: better handling of normal directories
        none=('pida-fm-none', False, True), 
        normal=('pida-fm-normal', False, False),
        error=('pida-fm-error', True, True),
        empty=('pida-fm-empty', False, True),
        modified=('pida-fm-modified', True, False),
        conflict=('pida-fm-conflict', True, True),
        removed=('pida-fm-removed', True, True),
        missing=('pida-fm-missing', True, False),
        new=('pida-fm-new', True, False),
        added=('pida-fm-new', True, False),
        max=('pida-fm-max', False, False),
        external=('pida-fm-external', False, True),
        )


def check_or_home(path):
    if not os.path.isdir(path):
        get_logger('pida.svc.filemanager').info(_("Can't open directory: %s") %path)
        return homedir
    return path



class FileEntry(object):
    """The model for file entries"""

    def __init__(self, name, parent_path, manager):
        self._manager = manager
        self.state = 'normal'
        self.name = name
        self.lower_name = self.name.lower()
        self.parent_path = parent_path
        self.path = os.path.join(parent_path, name)
        self.extension = os.path.splitext(self.name)[-1]
        self.extension_sort = self.extension, self.lower_name
        self.is_dir = os.path.isdir(self.path)
        self.is_dir_sort = not self.is_dir, self.lower_name
        self.visible = False

    @property
    def markup(self):
        return self.format(cgi.escape(self.name))

    @property
    def icon_stock_id(self):
        if path.isdir(self.path):
            return 'stock_folder'
        else:
            #TODO: get a real mimetype icon
            return 'text-x-generic'

    @property
    def state_markup(self):
        text = state_text.get(self.state, ' ')
        wrap = '<span weight="ultrabold"><tt>%s</tt></span>'
        return wrap%self.format(text)


    def format(self, text):
        color, b, i = state_style.get(self.state, (None, False, False))
        if color:
            color = self._manager.file_list.style.lookup_color(color).to_string()
        if not color:
            color = "black"
        if b:
            text = '<b>%s</b>' % text
        if i:
            text = '<i>%s</i>' % text
        return '<span color="%s">%s</span>' % (color, text)


class FilemanagerView(PidaView):

    _columns = [
        Column("icon_stock_id", use_stock=True),
        Column("state_markup", use_markup=True),
        Column("markup", use_markup=True),
        Column("lower_name", visible=False, searchable=True),
        ]

    label_text = _('Files')
    icon_name = 'file-manager'
    key = 'filemanager.list'

    def create_ui(self):
        self._vbox = gtk.VBox()
        self._vbox.show()
        self.create_toolbar()
        self._file_hidden_check_actions = {}
        self._create_file_hidden_check_toolbar()
        self.create_file_list()
        self._clipboard_file = None
        self._fix_paste_sensitivity()
        self.add_main_widget(self._vbox)

    def create_file_list(self):
        self.file_list = ObjectList()
        self.file_list.set_headers_visible(False)
        self.file_list.set_columns(self._columns);
        self.file_list.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        #XXX: real file
        self.file_list.get_treeview().connect('button-press-event',
            self.on_file_button_press_event)
        self.file_list.connect('selection-changed', self.on_selection_changed)
        self.file_list.connect('row-activated', self.on_file_activated)
        self.file_list.connect('right-click', self.on_file_right_click)
        self.entries = {}
        self.update_to_path(self.svc.path)
        self.file_list.show()
        self._vbox.pack_start(self.file_list)
        self._sort_combo = AttrSortCombo(self.file_list,
            [
                ('is_dir_sort', _('Directories First')),
                ('path', _('File Path')),
                ('lower_name', _('File Name')),
                ('name', _('File Name (Case Sensitive)')),
                ('extension_sort', _('Extension')),
                ('state', _('Version Control Status')),
            ],
            'is_dir_sort')
        self._sort_combo.show()
        self._vbox.pack_start(self._sort_combo, expand=False)
        self.on_selection_changed(self.file_list, None)

    def create_toolbar(self):
        self._uim = gtk.UIManager()
        self._uim.insert_action_group(self.svc.get_action_group(), 0)
        self._uim.add_ui_from_file(get_uidef_path('filemanager-toolbar.xml'))
        self._uim.ensure_update()
        self._toolbar = self._uim.get_toplevels('toolbar')[0]
        self._toolbar.set_style(gtk.TOOLBAR_ICONS)
        self._toolbar.set_icon_size(gtk.ICON_SIZE_MENU)
        self._vbox.pack_start(self._toolbar, expand=False)
        self._toolbar.show_all()

    def add_or_update_file(self, name, basepath, state, select=False):
        if basepath != self.path:
            return
        entry = self.entries.setdefault(name, FileEntry(name, basepath, self))
        entry.state = state

        self.show_or_hide(entry, select=select)

    def show_or_hide(self, entry, select=False):
        from operator import and_
        def check(checker):
            if (checker.identifier in self._file_hidden_check_actions) and \
               (self._file_hidden_check_actions[checker.identifier].get_active()):
                return checker(name=entry.name, path=entry.parent_path,
                    state=entry.state, )
            else:
                return True

        if self.svc.opt('show_hidden'):
            show = True
        else:
            show = all(check(x)
                        for x in self.svc.features['file_hidden_check'])

        if show:
            if entry.visible:
                self.file_list.update(entry)
            else:
                self.file_list.append(entry)
                entry.visible = True
            if select:
                self.file_list.select(entry)
        else:
            if entry.visible:
                self.file_list.remove(entry)
                entry.visible = False

    def update_to_path(self, new_path=None, select=None):
        if new_path is None:
            new_path = self.path
        else:
            self.path = check_or_home(new_path)

        self.file_list.clear()
        self.entries.clear()
        
        def work(basepath):
            dir_content = listdir(basepath)
            # add all files from vcs and remove the corresponding items 
            # from dir_content
            for item in self.svc.boss.cmd('versioncontrol', 'list_file_states',
              path=self.path):
                if (item[1] == self.path):
                    try:
                        dir_content.remove(item[0])
                    except:
                        pass
                    yield item
            # handle remaining files
            for filename in dir_content:
                if (path.isdir(path.join(basepath, filename))):
                    state = 'normal'
                else:
                    state = 'unknown'
                yield filename, basepath, state

        # wrap add_or_update_file to set select accordingly
        def _add_or_update_file(name, basepath, state):
            self.add_or_update_file(name, basepath, state, select=(name==select))

        GeneratorTask(work, _add_or_update_file).start(self.path)

        self.create_ancest_tree()

    # This is painful, and will always break
    # So use the following method instead
    def update_single_file(self, name, basepath):
        def _update_file(oname, obasepath, state):
            if oname == name and basepath == obasepath:
                if name not in self.entries:
                    self.entries[oname] = FileEntry(oname, obasepath, self)
                self.entries[oname].state = state
                self.show_or_hide(self.entries[oname])
        for lister in self.svc.features['file_lister']:
            GeneratorTask(lister, _update_file).start(self.path)

    def update_single_file(self, name, basepath, select=False):
        if basepath != self.path:
            return
        if name not in self.entries:
            self.entries[name] = FileEntry(name, basepath, self)
            self.show_or_hide(self.entries[name], select=select)

    def update_removed_file(self, filename):
        entry = self.entries.pop(filename, None)
        if entry is not None and entry.visible:
            self.file_list.remove(entry)

    def on_file_button_press_event(self, file_list, event):
        # unselect all rows if user clicked on the empty space below the last
        # row
        if (file_list.get_path_at_pos(int(event.x), int(event.y)) is None):
            file_list.get_selection().unselect_all()
            if (event.button == 3):
                # right click on base directory
                item = FileEntry(os.path.basename(self.path),
                    os.path.dirname(self.path), self)
                self.on_file_right_click(file_list, item, event)
            return True
        else:
            return False

    def create_dir(self, name=None):
        if not name:
            opts = DialogOptions().add('name', label=_("Directory name"), value="")
            create_gtk_dialog(opts, parent=self.svc.boss.window).run()
            name = opts.name
        if name:
            npath = os.path.join(self.path, opts.name)
            if not os.path.exists(npath):
                os.mkdir(npath)
            self.update_single_file(opts.name, self.path, select=True)
             
    def on_file_activated(self, rowitem, fileentry):
        if os.path.exists(fileentry.path):
            if fileentry.is_dir:
                self.svc.browse(fileentry.path)
            else:
                self.svc.boss.cmd('buffer', 'open_file', file_name=fileentry.path)
        else:
            self.update_removed_file(fileentry.name)

    def on_file_right_click(self, ol, item, event=None):
        if item.is_dir:
            self.svc.boss.cmd('contexts', 'popup_menu', context='dir-menu',
                          dir_name=item.path, event=event, filemanager=True) 
        else:
            self.svc.boss.cmd('contexts', 'popup_menu', context='file-menu',
                          file_name=item.path, event=event, filemanager=True)

    def on_selection_changed(self, ol, item):
        for act_name in ['toolbar_copy', 'toolbar_delete']:
            self.svc.get_action(act_name).set_sensitive(item is not None)

    def rename_file(self, old, new, entry):
        print 'renaming', old, 'to' ,new

    def create_ancest_tree(self):
        task = AsyncTask(self._get_ancestors, self._show_ancestors)
        task.start(self.path)

    def _on_act_up_ancestor(self, action, directory):
        self.svc.browse(directory)

    def _show_ancestors(self, ancs):
        toolitem = self.svc.get_action('toolbar_up').get_proxies()[0]
        menu = gtk.Menu()
        for anc in ancs:
            action = gtk.Action(anc, anc, anc, 'directory')
            action.connect('activate', self._on_act_up_ancestor, anc)
            menuitem = action.create_menu_item()
            menu.add(menuitem)
        menu.show_all()
        toolitem.set_menu(menu)

    def _get_ancestors(self, directory):
        ancs = [directory]
        while directory != '/':
            parent = os.path.dirname(directory)
            ancs.append(parent)
            directory = parent
        return ancs

    def _on_act_file_hidden_check(self, action, check):
        if (check.scope == filehiddencheck.SCOPE_GLOBAL):
            # global
            active_checker = self.svc.opt('file_hidden_check')
            if (action.get_active()):
                active_checker.append(check.identifier)
            else:
                active_checker.remove(check.identifier)
            self.svc.set_opt('file_hidden_check', active_checker)
        else:
            # project
            if (self.svc.current_project is not None):
                section = self.svc.current_project.options.get('file_hidden_check', {})
                section[check.identifier] = action.get_active()
                self.svc.current_project.options['file_hidden_check'] = section
        self.update_to_path()
    
    def __file_hidden_check_scope_project_set_active(self, action):
        """sets active state of a file hidden check action with
           scope = project
           relies on action name = identifier of checker"""
        if (self.svc.current_project is not None):
            section = self.svc.current_project.options.get('file_hidden_check')
            action.set_active(
              (section is not None) and
              (action.get_name() in section) and
              (section[action.get_name()] == 'True'))
        else:
            action.set_active(False)
        
    
    def refresh_file_hidden_check(self):
        """refreshes active status of actions of project scope checker"""
        for checker in self.svc.features['file_hidden_check']:
            if (checker.scope == filehiddencheck.SCOPE_PROJECT):
                action = self._file_hidden_check_actions[checker.identifier]
                self.__file_hidden_check_scope_project_set_active(action)
    
    def _create_file_hidden_check_toolbar(self):
        self._file_hidden_check_actions = {}
        menu = gtk.Menu()
        separator = gtk.SeparatorMenuItem()
        project_scope_count = 0
        menu.append(separator)
        for checker in self.svc.features['file_hidden_check']:
            action = gtk.ToggleAction(checker.identifier, checker.label,
              checker.label, None)
            # active?
            if (checker.scope == filehiddencheck.SCOPE_GLOBAL):
                action.set_active(
                    checker.identifier in self.svc.opt('file_hidden_check'))
            else:
                self.__file_hidden_check_scope_project_set_active(action)

            action.connect('activate', self._on_act_file_hidden_check, checker)
            self._file_hidden_check_actions[checker.identifier] = action
            menuitem = action.create_menu_item()
            if (checker.scope == filehiddencheck.SCOPE_GLOBAL):
                menu.prepend(menuitem)
            else:
                menu.append(menuitem)
                project_scope_count += 1
        menu.show_all()
        if (project_scope_count == 0):
            separator.hide()
        toolitem = None
        for proxy in self.svc.get_action('toolbar_hidden_menu').get_proxies():
            if (isinstance(proxy, DropDownMenuToolButton)):
                toolitem = proxy
                break
        if (toolitem is not None):
            toolitem.set_menu(menu)

    def get_selected_filename(self):
        fileentry = self.file_list.get_selected()
        if fileentry is not None:
            return fileentry.path

    def copy_clipboard(self):
        current = self.get_selected_filename()
        if os.path.exists(current):
            self._clipboard_file = current
        else:
            self._clipboard_file = None
        self._fix_paste_sensitivity()

    def _fix_paste_sensitivity(self):
        self.svc.get_action('toolbar_paste').set_sensitive(self._clipboard_file
                                                           is not None)

    def paste_clipboard(self):
        task = AsyncTask(self._paste_clipboard, lambda: None)
        task.start()

    def _paste_clipboard(self):
        newname = os.path.join(self.path, os.path.basename(self._clipboard_file))
        if newname == self._clipboard_file:
            self.svc.error_dlg(_('Cannot copy files to themselves.'))
            return
        if not os.path.exists(self._clipboard_file):
            self.svc.error_dlg(_('Source file has vanished.'))
        if os.path.exists(newname):
            self.svc.error_dlg(_('Destination already exists.'))
            return
        if os.path.isdir(self._clipboard_file):
            shutil.copytree(self._clipboard_file, newname)
        else:
            shutil.copy2(self._clipboard_file, newname)

    def remove_path(self, path):
        task = AsyncTask(self._remove_path, lambda: None)
        task.start(path)

    def _remove_path(self, path):
        if os.path.isdir(path):
            shutil.rmtree(path)
        else:
            os.remove(path)
        if path == self._clipboard_file:
            self._clipboard_file = None
            self._fix_paste_sensitivity()

class FilemanagerEvents(EventsConfig):

    def create(self):
        self.publish(
                'browsed_path_changed',
                'file_renamed')
        
        self.subscribe('file_renamed', self.svc.rename_file)

    def subscribe_all_foreign(self):
        self.subscribe_foreign('project', 'project_switched',
                                     self.svc.on_project_switched)
        self.subscribe_foreign('plugins', 'plugin_started',
            self.on_plugin_started)
        self.subscribe_foreign('plugins', 'plugin_stopped',
            self.on_plugin_stopped);
        self.subscribe_foreign('contexts', 'show-menu',
            self.on_contexts__show_menu)
        self.subscribe_foreign('contexts', 'menu-deactivated',
            self.on_contexts__menu_deactivated)

    def on_plugin_started(self, plugin):
        if (plugin.features.has_foreign('filemanager', 'file_hidden_check')):
            self.svc.refresh_file_hidden_check_menu()
    
    def on_plugin_stopped(self, plugin):
        self.svc.refresh_file_hidden_check_menu()

    def on_contexts__show_menu(self, menu, context, **kw):        
        if (kw.has_key('filemanager')):
            if (context == 'file-menu'):
                self.svc.get_action('delete-file').set_visible(kw['file_name'] is not None)
            else:
                self.svc.get_action('delete-dir').set_visible(
                    kw['dir_name'] != self.svc.get_view().path)
        else:
            self.svc.get_action('delete-file').set_visible(False)
            self.svc.get_action('delete-dir').set_visible(False)            
            self.svc.get_action('browse-for-file').set_visible(
                (kw.has_key('file_name') and kw['file_name'] is not None) or
                (kw.has_key('dir_name') and kw['dir_name'] is not None))

    def on_contexts__menu_deactivated(self, menu, context, **kw):
        if (kw.has_key('filemanager')):
            if (context == 'file-menu'):
                self.svc.get_action('delete-file').set_visible(False)
            else:
                self.svc.get_action('delete-dir').set_visible(False)


class FilemanagerCommandsConfig(CommandsConfig):
    def browse(self, new_path):
        self.svc.browse(new_path)

    def get_browsed_path(self):
        return self.svc.path

    def get_view(self):
        return self.svc.get_view()

    def present_view(self):
        return self.svc.boss.cmd('window', 'present_view',
            view=self.svc.get_view())

    def update_file(self, filename, dirname):
        if dirname == self.svc.get_view().path:
            self.svc.get_view().update_single_file(filename, dirname)

    def update_removed_file(self, filename, dirname):
        if dirname == self.svc.get_view().path:
            self.svc.get_view().update_removed_file(filename)

    def refresh(self):
        self.svc.get_view().update_to_path()


class FilemanagerFeatureConfig(FeaturesConfig):

    def create(self):
        self.publish('file_manager')
        self.publish('file_hidden_check')
        self.subscribe('file_hidden_check', self.dot_files)
        self.subscribe('file_hidden_check', self.regex)

    def subscribe_all_foreign(self):
        self.subscribe_foreign('contexts', 'file-menu',
            (self.svc.get_action_group(), 'filemanager-file-menu.xml'))
        self.subscribe_foreign('contexts', 'dir-menu',
            (self.svc.get_action_group(), 'filemanager-dir-menu.xml'))

    # File Hidden Checks
    @filehiddencheck.fhc(filehiddencheck.SCOPE_GLOBAL, _("Hide Dot-Files"))
    def dot_files(self, name, path, state):
        return name[0] != '.'

    @filehiddencheck.fhc(filehiddencheck.SCOPE_GLOBAL, 
        _("Hide by User defined Regular Expression"))
    def regex(self, name, path, state):
        _re = self.svc.opt('hide_regex')
        if not re:
            return True
        else:
            return re.match(_re, name) is None


class FileManagerOptionsConfig(OptionsConfig):
    def create_options(self):
        self.create_option(
                'show_hidden',
                _('Show hidden files'),
                bool,
                True,
                _('Shows hidden files'),
                workspace=True)
        self.create_option(
                'file_hidden_check',
                _('Used file hidden checker'),
                list,
                [],
                _('The used file hidden checker'),
                workspace=True)
        
        self.create_option(
                'last_browsed_remember',
                _('Remember last Path'),
                bool,
                True,
                _('Remembers the last browsed path'))
        
        self.create_option(
                'last_browsed',
                _('Last browsed Path'),
                str,
                path.expanduser('~'),
                _('The last browsed path'),
                safe=False,
                workspace=True)
        
        self.create_option(
                'hide_regex',
                _('Hide regex'),
                str,
                '^\.|.*~|.*\.py[co]$',
                _('Hides files that match the regex'))

class FilemanagerDbusConfig(DbusConfig):
    @IEXPORT(in_signature="s")
    def browse(self, path):
        self.svc.browse(path)

    @IEXPORT(out_signature="s")
    def get_browsed_path(self):
        return self.svc.path

    @IEXPORT(in_signature="s")
    def create_dir(self, path):
        self.svc.create_dir(path)

    @IEXPORT()
    def go_current_file(self):
        self.svc.go_current_file()

    @IEXPORT()
    def go_up(self):
        self.svc.go_up()

    @IEXPORT()
    def refresh_file_hidden_check_menu(self):
        self.svc.refresh_file_hidden_check_menu()

    @IEXPORT()
    def present_view(self):
        self.svc.commands.present_view()

    @IEXPORT()
    def refresh(self):
        self.svc.commands.refresh()



class FileManagerActionsConfig(ActionsConfig):

    def create_actions(self):
        self.create_action(
            'delete-file',
            TYPE_NORMAL,
            _('Delete File'),
            _('Delete selected file'),
            gtk.STOCK_DELETE,
            self.on_delete
        )
        
        self.create_action(
            'browse-for-file',
            TYPE_NORMAL,
            _('Browse the file directory'),
            _('Browse the parent directory of this file'),
            'file-manager',
            self.on_browse_for_file,
        )
        
        self.create_action(
            'delete-dir',
            TYPE_NORMAL,
            _('Delete Directory'),
            _('Delete selected directory'),
            gtk.STOCK_DELETE,
            self.on_delete
        )

        self.create_action(
            'browse-for-dir',
            TYPE_NORMAL,
            _('Browse the directory'),
            _('Browse the directory'),
            'file-manager',
            self.on_browse_for_dir,
        )

        self.create_action(
            'show_filebrowser',
            TYPE_NORMAL,
            _('Show _file browser'),
            _('Show the file browser view'),
            'file-manager',
            self.on_show_filebrowser,
            '<Shift><Control>f'
        )

        self.create_action(
            'toolbar_up',
            TYPE_MENUTOOL,
            _('Go Up'),
            _('Go to the parent directory'),
            gtk.STOCK_GO_UP,
            self.on_toolbar_up,
            '<Shift><Control>Up',
        )

        self.create_action(
            'toolbar_terminal',
            TYPE_NORMAL,
            _('Open Terminal'),
            _('Open a terminal in this directory'),
            'terminal',
            self.on_toolbar_terminal,
        )

        self.create_action(
            'toolbar_refresh',
            TYPE_NORMAL,
            _('Refresh Directory'),
            _('Refresh the current directory'),
            gtk.STOCK_REFRESH,
            self.on_toolbar_refresh,
        )

        self.create_action(
            'toolbar_projectroot',
            TYPE_NORMAL,
            _('Project Root'),
            _('Browse the root of the current project'),
            'user-home',
            self.on_toolbar_projectroot,
        )

        self.create_action(
            'toolbar_create_dir',
            TYPE_NORMAL,
            _('Create Directory'),
            _('Create a new directory'),
            gtk.STOCK_DIRECTORY,
            self.on_toolbar_create_dir,
        )

        self.create_action(
            'toolbar_home',
            TYPE_NORMAL,
            _('Home'),
            _('Browse your home directory'),
            'user-home',
            self.on_toolbar_home,
        )
        
        self.create_action(
            'toolbar_current_file',
            TYPE_NORMAL,
            _('Current Directory'),
            _('Browse directory of current file'),
            gtk.STOCK_GOTO_FIRST,
            self.on_toolbar_current_file,
        )


        self.create_action(
            'toolbar_copy',
            TYPE_NORMAL,
            _('Copy File'),
            _('Copy selected file to the clipboard'),
            gtk.STOCK_COPY,
            self.on_toolbar_copy,
        )

        self.create_action(
            'toolbar_paste',
            TYPE_NORMAL,
            _('Paste File'),
            _('Paste selected file from the clipboard'),
            gtk.STOCK_PASTE,
            self.on_toolbar_paste,
        )

        self.create_action(
            'toolbar_delete',
            TYPE_NORMAL,
            _('Delete File'),
            _('Delete the selected file'),
            gtk.STOCK_DELETE,
            self.on_delete,
        )
        self.create_action(
            'toolbar_toggle_hidden',
            TYPE_TOGGLE,
            _('Show Hidden Files'),
            _('Show hidden files'),
            gtk.STOCK_SELECT_ALL,
            self.on_toggle_hidden,
        )
        self.create_action(
            'toolbar_hidden_menu',
            TYPE_DROPDOWNMENUTOOL,
            None,
            _('Setup which kind of files should be hidden'),
            None,
            None,
        )


    def on_browse_for_file(self, action):
        new_path = path.dirname(action.contexts_kw['file_name'])
        self.svc.cmd('browse', new_path=new_path)
        self.svc.cmd('present_view')


    def on_browse_for_dir(self, action):
        new_path = action.contexts_kw['dir_name']
        self.svc.cmd('browse', new_path=new_path)
        self.svc.cmd('present_view')

    def on_show_filebrowser(self, action):
        self.svc.cmd('present_view')
    
    def on_toolbar_create_dir(self, action):
        self.svc.create_dir()

    def on_toolbar_up(self, action):
        self.svc.go_up()

    def on_toolbar_home(self, action):
        self.svc.cmd('browse', new_path=homedir)
    
    def on_toolbar_current_file(self, action):
        self.svc.go_current_file()

    def on_toolbar_terminal(self, action):
        self.svc.boss.cmd('commander','execute_shell', cwd=self.svc.path)

    def _on_menu_down(self, menu, action):
        action.set_active(False)
        print "down"
    
    def on_toggle_hidden(self, action):
        self.svc.set_opt('show_hidden', action.get_active())
        self.on_toolbar_refresh(action)

    def on_toolbar_refresh(self, action):
        self.svc.get_view().update_to_path()

    def on_toolbar_projectroot(self, action):
        self.svc.browse(self.svc.current_project.source_directory)

    def on_toolbar_copy(self, action):
        self.svc.get_view().copy_clipboard()

    def on_toolbar_paste(self, action):
        self.svc.get_view().paste_clipboard()

    def on_delete(self, action):
        current = self.svc.get_view().get_selected_filename()
        if current is not None:
            if self.svc.yesno_dlg(
                _('Are you sure you want to delete the selected file: %s?'
                % current)
            ):
                self.svc.get_view().remove_path(current)

                if not self.svc.boss.get_service('filewatcher').started:
                    self.svc.get_view().update_to_path()



# Service class
class Filemanager(Service):
    """the Filemanager service"""

    options_config = FileManagerOptionsConfig
    features_config = FilemanagerFeatureConfig
    events_config = FilemanagerEvents
    dbus_config = FilemanagerDbusConfig
    commands_config = FilemanagerCommandsConfig
    actions_config = FileManagerActionsConfig

    def pre_start(self):
        self.path = check_or_home(self.opt('last_browsed'))
        self.current_project = None
        self.file_view = FilemanagerView(self)


    def start(self):
        acts = self.boss.get_service('window').actions
        
        acts.register_window(self.file_view.key,
                             self.file_view.label_text)
        
        self.on_project_switched(self.current_project)
        self.emit('browsed_path_changed', path=self.path)
        self.get_action('toolbar_toggle_hidden').set_active(
                self.opt('show_hidden'))
        # FIXME: WTF WTF WTF WTF is fixing this the empty icons. 
        # I don't get it ! and why the hack is this happening
        for x in self.actions.list_actions():
            for p in x.get_proxies():
                if x.props.stock_id is not None:
                    p.set_stock_id(x.props.stock_id)

    def get_view(self):
        return self.file_view
   
    def browse(self, new_path, select=None):
        new_path = path.abspath(new_path)

        if new_path == self.path:
            return
        else:
            self.path = new_path
            self.set_opt('last_browsed', new_path)
            self.file_view.update_to_path(new_path, select=select)
        self.emit('browsed_path_changed', path=new_path)

    def create_dir(self, name=None):
        self.file_view.create_dir(name=name)

    def go_current_file(self):
        cd = self.boss.cmd('buffer', 'get_current')
        if cd and not cd.is_new:
            self.browse(cd.directory)

    def go_up(self):
        oldname = path.basename(self.path)
        dir = path.dirname(self.path)
        if not dir:
            dir = "/" #XXX: unportable, what about non-unix
        self.browse(dir, select=oldname)

    def rename_file(self, old, new, basepath):
        pass

    def refresh_file_hidden_check_menu(self):
        self.get_view()._create_file_hidden_check_toolbar()
    
    def on_project_switched(self, project):
        self.current_project = project
        self.get_action('toolbar_projectroot').set_sensitive(project is not None)
        if self.file_view:
            self.file_view.refresh_file_hidden_check()

# Required Service attribute for service loading
Service = Filemanager



# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79: