This file is indexed.

/usr/share/caja-python/extensions/folder-color.py is in folder-color-caja 0.0.79-0ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
# -*- coding: utf-8 -*-
# Folder Color 0.0.79
# Copyright (C) 2012-2015 Marcos Alvarez Costales https://launchpad.net/~costales
#
# Folder Color 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.
# 
# Folder Color 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 Folder Color; if not, see http://www.gnu.org/licenses
# for more information.

import os, urllib, gettext, glob, webbrowser, operator, shutil, ConfigParser, subprocess
from gi.repository import Caja, Gtk, GObject, Gio, GLib

# i18n
gettext.textdomain('folder-color-common')
_ = gettext.gettext


class FolderColor:
    """Theme/icon properties"""
    def __init__(self, remove_pid=True):
        self.lock = Lock()
        
        self.DEFAULT_PATH_THEME = ''
        
        self.PLACES       = 'places'
        self.EMBLEMS      = 'emblems'
        self.CUSTOM       = 'custom'
        self.GLOBALCOLOR  = 'globalcolor'
        
        self.FOLDER      = 'folder'
        self.PRE_PLACES  = 'folder_color'
        self.PRE_EMBLEMS = 'folder_emblem'
        self.PRE_CUSTOMS = 'folder_custom'
        
        self.SEARCH_PLACES      = 'folder_color_*.svg'
        self.SEARCH_EMBLEMS     = 'folder_emblem_*.svg'
        self.SEARCH_CUSTOMS     = 'folder_custom*.svg'
        self.SEARCH_GLOBALCOLOR = 'folder_color_globalcolor.svg'
        
        self.CHECK_PLACE       = 'folder_color_blue'
        self.CHECK_EMBLEM      = 'folder_emblem_favorite'
        self.CHECK_CUSTOM      = 'folder_custom'
        self.CHECK_GLOBALCOLOR = 'folder_color_globalcolor'
        
        self.EXTRA_HOME   = 'folder_extraicons_%s_home'
        self.EXTRA_REMOTE = 'folder_extraicons_%s_remote'
        self.EXTRA_RECENT = 'folder_extraicons_%s_recent'
        
        self.DESKTOP   = 'desktop'
        self.DOCUMENTS = 'documents'
        self.DOWNLOADS = 'downloads'
        self.MUSIC     = 'music'
        self.PICTURES  = 'pictures'
        self.PUBLIC    = 'public'
        self.TEMPLATES = 'templates'
        self.VIDEOS    = 'videos'
        
        self.DEFAULT_ICONS   = ('undo', 'edit', 'picker', 'preferences', 'default', self.DESKTOP, self.DOCUMENTS, self.DOWNLOADS, self.MUSIC, self.PICTURES, self.PUBLIC, self.TEMPLATES, self.VIDEOS)
        self.DEFAULT_FOLDERS = self._get_default_folders()
        self.ICON_RESOLUTIONS = {'16': '16x16', '22': '22x22', '24': '24x24', '32': '32x32', '48': '48x48', '64': '64x64'}
        
        self.SYSTEM_PATH_THEME = '/usr/share/icons'
        self.USER_PATH_THEME   = os.path.join(os.getenv('HOME'), '.icons')
        self.CFG_PATH          = os.path.join(os.getenv('HOME'), '.config', 'folder-color')
        self.CFG_PATH_CUSTOM   = os.path.join(self.CFG_PATH, 'custom_icons')
        self.HIDE_DONATION     = os.path.join(self.CFG_PATH, 'hide_donation')
        self.URL_DONATE        = 'http://gufw.org/donate_foldercolor'
        
        self.GRADIENT_RANGE = 15
        self.VALUE_LIGHT  = 'value_light'
        self.VALUE_MIDDLE = 'value_middle'
        self.VALUE_DARK   = 'value_dark'
        
        # Caja crashed? Allow future Preference dialogs
        if remove_pid:
            self.lock.remove()
    
    def get_iconname(self, folder, name, what='places', get_px='48'):
        """For 'green' returns folder_color_green_downloads"""
        if what == self.PLACES:
            prefix = self.PRE_PLACES
        elif what == self.EMBLEMS:
            prefix = self.PRE_EMBLEMS
        elif what == self.CUSTOM:
            prefix = self.FOLDER
        else:
            return ''
        
        if folder in self.DEFAULT_FOLDERS:
            iconname = '_'.join([prefix, name.replace(' ', '_').lower(), self.DEFAULT_FOLDERS[folder]])
            filename = ''.join([self.get_path(what, get_px), iconname, '.svg'])
            if os.path.isfile(filename): # Exist?
                return iconname
        
        iconname = '_'.join([prefix, name.replace(' ', '_').lower()])
        return iconname
    
    def get_filename(self, icon, extended=True):
        """From a complete path, returns green_downloads | folder_color_green_downloads"""
        icon_name = ''.join(icon.split('/')[-1:]).replace('.svg', '')
        if not extended:
            icon_name = icon_name.replace(self.PRE_PLACES, '').replace(self.PRE_EMBLEMS, '').replace('_', ' ').strip()
        return icon_name
    
    def get_path(self, what='places', get_px='48'):
        """Get current path. By example: /usr/share/icons/hicolor/48x48/places/"""
        icon = Gtk.IconTheme.get_default()
        
        if what == self.PLACES:
            icon_path = icon.lookup_icon(self.CHECK_PLACE, int(get_px), 0)
        elif what == self.EMBLEMS:
            icon_path = icon.lookup_icon(self.CHECK_EMBLEM, 24, 0)
        elif what == self.CUSTOM:
            icon_path = icon.lookup_icon(self.CHECK_CUSTOM, int(get_px), 0)
        elif what == self.GLOBALCOLOR:
            icon_path = icon.lookup_icon(self.CHECK_GLOBALCOLOR, 16, 0)
        else:
            return ''
        
        try:
            path = icon_path.get_filename()
        except:
            return ''
        
        filename = ''.join(path.split('/')[-1:])
        return path.replace(filename, '')
    
    def get_available_icons(self, what='places'):
        """Returns: '/usr/share/icons/hicolor', {'blue':'Azul', 'yellow':'Amarillo'}"""
        path = ''
        names_sorted = {}
        first_iter = True
        
        if what == self.PLACES:
            path = ''.join([self.get_path(what), self.SEARCH_PLACES])
        elif what == self.EMBLEMS:
            path = ''.join([self.get_path(what), self.SEARCH_EMBLEMS])
        elif what == self.CUSTOM:
            path = ''.join([self.get_path(what), self.SEARCH_CUSTOMS])
        elif what == self.GLOBALCOLOR:
            path = ''.join([self.get_path(what), self.SEARCH_GLOBALCOLOR])
        else:
            return available_items
        
        available_icons = glob.glob(path)
        
        for icon in available_icons:
            if any(not_count in icon for not_count in self.DEFAULT_ICONS):
                continue
            if what != self.CUSTOM and self.CUSTOM in icon:
                continue
            
            if first_iter: # Get default path
                first_iter = False
                path = '/'.join(icon.split('/')[:5])
            
            # Get icons names and its translations
            color = self.get_filename(icon, False)
            if color:
                names_sorted[color] = _(color.title()) # blue = Blue
        
        names = sorted(names_sorted.items(), key=operator.itemgetter(1))
        return path, names
    
    def get_current_icontheme(self):
        """Returns all data about current theme"""
        settings = Gtk.Settings.get_default()
        name = settings.get_property('gtk-icon-theme-name').replace('.foldercolor', '')
        
        # User or system theme?
        user_path   = os.path.join(self.SYSTEM_PATH_THEME, name)
        system_path = os.path.join(self.USER_PATH_THEME,   name)
        if os.path.exists(user_path):
            path = user_path
        elif os.path.exists(system_path):
            path = system_path
        else:
            return '', '', ''
        
        index = os.path.join(path, 'index.theme')
        return path, name, index
    
    def _reload_icon(self, folder):
        """Reload the current folder icon"""
        proc = subprocess.Popen(['touch', folder], shell=False)
        proc.communicate()
    
    def _get_default_folders(self):
        """Default user folders"""
        folders = {}
        folders[GLib.get_user_special_dir(GLib.USER_DIRECTORY_DESKTOP)]      = self.DESKTOP  
        folders[GLib.get_user_special_dir(GLib.USER_DIRECTORY_DOCUMENTS)]    = self.DOCUMENTS
        folders[GLib.get_user_special_dir(GLib.USER_DIRECTORY_DOWNLOAD)]     = self.DOWNLOADS
        folders[GLib.get_user_special_dir(GLib.USER_DIRECTORY_MUSIC)]        = self.MUSIC    
        folders[GLib.get_user_special_dir(GLib.USER_DIRECTORY_PICTURES)]     = self.PICTURES 
        folders[GLib.get_user_special_dir(GLib.USER_DIRECTORY_PUBLIC_SHARE)] = self.PUBLIC   
        folders[GLib.get_user_special_dir(GLib.USER_DIRECTORY_TEMPLATES)]    = self.TEMPLATES
        folders[GLib.get_user_special_dir(GLib.USER_DIRECTORY_VIDEOS)]       = self.VIDEOS   
        return folders
    
    def _unset_attrib(self, folder_name):
        """Restore to default"""
        folder = Gio.File.new_for_path(folder_name)
        info = folder.query_info('metadata::custom-icon-name', 0, None)
        info.set_attribute('metadata::custom-icon',      Gio.FileAttributeType.INVALID, 0)
        info.set_attribute('metadata::custom-icon-name', Gio.FileAttributeType.INVALID, 0)
        return folder, info
    
    def _write_attrib(self, folder, info):
        """Write attributes to folder"""
        folder.set_attributes_from_info(info, 0, None)
    
    def restore_icon(self, folder_name):
        """Restore by default"""
        folder, info = self._unset_attrib(folder_name)
        self.set_emblem(folder_name, '')
        self._write_attrib(folder, info)
        self._reload_icon(folder_name)
    
    def set_icon(self, folder_name, color):
        """Set color to a folder"""
        folder, info = self._unset_attrib(folder_name) # Restore because I don't know if I set previously with custom-icon or custom-icon-name
        info.set_attribute_string("metadata::custom-icon", "".join(["file://", self.get_path(), self.get_filename(color), ".svg"]))
        self._write_attrib(folder, info)
        self._reload_icon(folder_name)
    
    def set_icon_custom(self, folder_name, src_file, dst_file, custom_colors):
        """Set a custom color to a folder"""
        folder, info = self._unset_attrib(folder_name) # Restore because I don't know if I set previously with custom-icon or custom-icon-name
        self._generate_custom_file(src_file, dst_file, custom_colors)
        info.set_attribute_string('metadata::custom-icon', ''.join(['file://', dst_file]))
        self._write_attrib(folder, info)
        self._reload_icon(folder_name)
    
    def set_emblem(self, folder, emblem=''):
        """Set an emblem"""
        # TODO: Use Gio
        if emblem:
            cmd = ['gvfs-set-attribute', '-t', 'stringv', folder, 'metadata::emblems', emblem]
        else:
            cmd = ['gvfs-set-attribute', '-t', 'unset', folder, 'metadata::emblems']
        
        proc = subprocess.Popen(cmd, shell=False)
        proc.communicate()
        
        self._reload_icon(folder)
    
    def custom_color_dialog(self):
        """Shows the dialog and return the color"""
        dialog = Gtk.ColorSelectionDialog()
        
        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            # Color
            color = dialog.get_color_selection().get_current_color()
            dialog.destroy()
            red   = int(color.red   / 256)
            green = int(color.green / 256)
            blue  = int(color.blue  / 256)
            # Light
            hex_light = "%02x%02x%02x" % (red, green, blue)
            # Middle
            red = red - self.GRADIENT_RANGE
            if red < 0:
                red = 0
            green = green - self.GRADIENT_RANGE
            if green < 0:
                green = 0
            blue = blue - self.GRADIENT_RANGE
            if blue < 0:
                blue = 0
            hex_middle = "%02x%02x%02x" % (red, green, blue)
            # Dark
            red = red - self.GRADIENT_RANGE
            if red < 0:
                red = 0
            green = green - self.GRADIENT_RANGE
            if green < 0:
                green = 0
            blue  = blue  - self.GRADIENT_RANGE
            if blue < 0:
                blue = 0
            hex_dark = "%02x%02x%02x" % (red, green, blue)
            return (hex_light, hex_middle, hex_dark)
        
        dialog.destroy()
        return None
    
    def _generate_custom_file(self, src_file, dst_file, colors):
        """Parsing template to a custom color"""
        f_input  = open(src_file, 'r') # This has to exists always
        f_output = open(dst_file, 'w')
        
        f_generate  = f_input.read().replace(self.VALUE_LIGHT, colors[0]).replace(self.VALUE_MIDDLE, colors[1]).replace(self.VALUE_DARK, colors[2])
        f_output.write(f_generate)


class FolderColorMenu(GObject.GObject, Caja.MenuProvider):
    """Folder Color Menu"""
    def __init__(self):
        self.foldercolor = FolderColor()
        self.lock = Lock()
        self.globalcolor = GlobalColor()
        
        dummy_i18n = (_("Brown"), _("Blue"), _("Green"), _("Grey"), _("Orange"), _("Pink"), _("Red"), _("Purple"), _("Yellow"), _("Favorite"), _("Finished"), _("Important"), _("In Progress")) # Need i18n, because colors/emblems are dynamic now
        
        if not os.path.exists(self.foldercolor.CFG_PATH_CUSTOM):
            try:
                os.makedirs(self.foldercolor.CFG_PATH_CUSTOM)
            except OSError as exception:
                pass
            except:
                pass
    
    def get_file_items(self, window, items):
        """Caja invoke this function in its startup > Then, create menu entry"""
        # Checks
        if not self._check_generate_menu(items):
            return
        # Return menu
        return self._generate_menu(items, self._check_generate_restore(items))
    
    def _check_generate_restore(self, items):
        # For each dir, search custom icon or emblem
        for item in items:
            if item.is_gone():
                continue
            
            folder_name = urllib.unquote(item.get_uri()[7:])
            folder = Gio.File.new_for_path(folder_name)
            info = folder.query_info('metadata', 0, None)
            if info.get_attribute_as_string('metadata::custom-icon-name'):
                return True
            if info.get_attribute_as_string('metadata::custom-icon'):
                return True
            if info.get_attribute_as_string('metadata::emblems'):
                return True
        
        return False
    
    def _check_generate_menu(self, items):
        """Show the menu?"""
        # No items selected
        if not len(items):
            return False
        
        # Are there Folder Color icons available?
        if not len(self.foldercolor.get_available_icons('places')[1]):
            return False
        
        # Check only folders
        for item in items:
            # GNOME can only handle files
            if item.get_uri_scheme() != 'file':
                return False
            # Only folders
            if not item.is_directory():
                return False
        
        # All OK > Generate menu
        return True
    
    def _generate_menu(self, items, show_restore):
        """Generate menu: Color | Custom? | Restore | Emblems? | Preferences"""
        # Main menu [1 or +1 folder(s)]
        if len(items) > 1:
            top_menuitem = Caja.MenuItem(name='ChangeFolderColorMenu::Top', label=_("Folders' Color"), icon='folder_color_picker')
        else:
            top_menuitem = Caja.MenuItem(name='ChangeFolderColorMenu::Top', label=_("Folder's Color"),  icon='folder_color_picker')
        submenu = Caja.Menu()
        top_menuitem.set_submenu(submenu)
        
        # Colors
        self.DEFAULT_PATH_THEME,colors = self.foldercolor.get_available_icons()
        for color in colors:
            name = ''.join(['ChangeFolderColorMenu::Colors"', color[0], '"'])
            item = Caja.MenuItem(name=name, label=color[1], icon=self.foldercolor.get_iconname('None', color[0]))
            item.connect('activate', self._menu_activate_color, color[0], items)
            submenu.append_item(item)
        
        # Custom color
        path_theme,customs = self.foldercolor.get_available_icons('custom')
        if len(customs):
            if path_theme == self.DEFAULT_PATH_THEME: # Show custom only if it exists in the current theme
                item_custom = Caja.MenuItem(name=''.join(['ChangeFolderColorMenu::"custom"']), label=_("Custom"), icon='folder_color_edit')
                item_custom.connect('activate', self._menu_activate_custom, items)
                submenu.append_item(item_custom)
        
        # Emblems
        path_theme,emblems = self.foldercolor.get_available_icons('emblems')
        for i,emblem in enumerate(emblems):
            if not i: # Separator
                if path_theme != self.DEFAULT_PATH_THEME: # Show emblems only if them exist in the current theme
                    break
                item_sep = Caja.MenuItem(name='ChangeFolderColorMenu::Sep1', label=_("Categorize:"), sensitive=False)
                submenu.append_item(item_sep)
            
            name = ''.join(['ChangeFolderEmblemMenu::Emblem"', emblem[0], '"'])
            item = Caja.MenuItem(name=name, label=emblem[1], icon=self.foldercolor.get_iconname('None', emblem[0], 'emblems'))
            item.connect('activate', self._menu_activate_emblem, emblem[0], items)
            submenu.append_item(item)
        
        # Restore
        if show_restore:
            item_sep = Caja.MenuItem(name='ChangeFolderEmblemMenu::Sep', label=_("Restore:"), sensitive=False)
            submenu.append_item(item_sep)
            
            item_restore = Caja.MenuItem(name='ChangeFolderColorMenu::Restore', label=_("Default"), icon='folder_color_undo')
            item_restore.connect('activate', self._menu_activate_restore, items)
            submenu.append_item(item_restore)
        
        # Global Color
        path_theme,customs = self.foldercolor.get_available_icons('globalcolor')
        if len(customs) and path_theme == self.DEFAULT_PATH_THEME: # Show Global Color only if the theme wants that
            item_sep = Caja.MenuItem(name='ChangeFolderColorMenu::Sep2', label=_("Edit:"), sensitive=False)
            submenu.append_item(item_sep)
            item = Caja.MenuItem(name=''.join(['ChangeFolderColorMenu::"preferences"']), label=_("Global Color"), icon='folder_color_globalcolor')
            item.connect('activate', self._menu_activate_preferences)
            submenu.append_item(item)
        elif not os.path.exists(self.foldercolor.HIDE_DONATION):
            item_sep = Caja.MenuItem(name='ChangeFolderColorMenu::Sep2', label=_("Support:"), sensitive=False)
            submenu.append_item(item_sep)
            item = Caja.MenuItem(name=''.join(['ChangeFolderColorMenu::"donate"']), label=_("Donate? Click to hide"))
            item.connect('activate', self._on_donate_menu)
            submenu.append_item(item)
        
        return top_menuitem,
    
    def _menu_activate_color(self, menu, color, folders):
        """Set Custom Color"""
        for each_folder in folders:
            if each_folder.is_gone():
                continue
            
            folder_name = urllib.unquote(each_folder.get_uri()[7:])
            new_color = self.foldercolor.get_iconname(folder_name, color)
            
            self.foldercolor.set_icon(folder_name, new_color)
    
    def _menu_activate_custom(self, menu, folders):
        """Set Color"""
        # Custom
        custom_colors = None
        custom_colors = self.foldercolor.custom_color_dialog()
        if custom_colors == None: # Cancel?
            return
        
        for each_folder in folders:
            if each_folder.is_gone():
                continue
            
            folder_name = urllib.unquote(each_folder.get_uri()[7:])
            src_file = ''.join([self.foldercolor.get_path('custom'), self.foldercolor.get_iconname(folder_name, 'custom', 'custom'), '.svg'])
            dst_file = ''.join([self.foldercolor.CFG_PATH_CUSTOM, '/', self.foldercolor.get_iconname(folder_name, 'custom', 'custom'), '_', custom_colors[0], '.svg'])
            
            self.foldercolor.set_icon_custom(folder_name, src_file, dst_file, custom_colors)
    
    def _menu_activate_restore(self, menu, folders):
        """Restore Color"""
        for each_folder in folders:
            if each_folder.is_gone():
                continue
            
            folder_name = urllib.unquote(each_folder.get_uri()[7:])
            
            self.foldercolor.restore_icon(folder_name)
    
    def _menu_activate_emblem(self, menu, emblem, folders):
        """Click on emblem"""
        for each_folder in folders:
            if each_folder.is_gone():
                continue
            
            folder_name = urllib.unquote(each_folder.get_uri()[7:])
            new_emblem = self.foldercolor.get_iconname(folder_name, emblem, 'emblems')
            
            self.foldercolor.set_emblem(folder_name, new_emblem)
    
    def _menu_activate_preferences(self, btn):
        if self.lock.check(): # 1 dialog instance
            return
        self.lock.create()
        
        win = Gtk.Window()
        win.set_border_width(10)
        win.set_position(Gtk.WindowPosition.CENTER)
        win.set_title(_("Folder Color Preferences"))
        win.set_resizable(False)
        
        # Change global color
        vbox = Gtk.VBox(spacing=6)
        
        # Add current theme colors
        hbox = Gtk.HBox(spacing=6)
        # Colors
        name_colors = Gtk.ListStore(str, str)
        colors = self.foldercolor.get_available_icons()[1]
        for color in colors:
            name_colors.append([color[1], color[0]])
        name_colors.append([_("Default"), 'default'])
        renderer_text = Gtk.CellRendererText()
        self.cb_colors = Gtk.ComboBox.new_with_model(name_colors)
        self.cb_colors.pack_start(renderer_text, True)
        self.cb_colors.add_attribute(renderer_text, "text", 0)
        self.cb_colors.set_entry_text_column(1)
        self.cb_colors.set_active(0)
        
        label = Gtk.Label(_("Global Color:"))
        button = Gtk.Button(_("Apply"))
        button.connect('clicked', self._on_color_changed)
        hbox.pack_start(label, False, False, 0)
        hbox.pack_start(self.cb_colors, False, False, 0)
        hbox.pack_start(button, False, False, 0)
        vbox.pack_start(hbox, False, False, 0)
        # Donate
        if not os.path.exists(self.foldercolor.HIDE_DONATION):
            self.vbox_donate = Gtk.VBox(spacing=6)
            self.vbox_donate.pack_start(Gtk.HSeparator(), True, True, 0)
            link_donate = Gtk.LinkButton(self.foldercolor.URL_DONATE, _("Donate? Click to hide"))
            link_donate.set_tooltip_text(_("Thanks in advance!"))
            link_donate.connect("clicked", self._on_donate_hide)
            hbox = Gtk.HBox(spacing=6)
            hbox.pack_start(link_donate, True, True, 0)
            self.vbox_donate.pack_start(hbox, True, True, 0)
            vbox.pack_start(self.vbox_donate, True, True, 0)
        
        win.add(vbox)
        win.connect('delete-event', self._close_win)
        win.show_all()
        Gtk.main()
    
    def _on_donate_menu(self, btn):
        """Open from contextual menu"""
        webbrowser.open(self.foldercolor.URL_DONATE)
        try:
            os.makedirs(self.foldercolor.HIDE_DONATION)
        except OSError as exception:
            pass
        except:
            pass
    
    def _on_donate_hide(self, null):
        """Open from global color window"""
        self.vbox_donate.hide()
        # Hide donation after show it
        try:
            os.makedirs(self.foldercolor.HIDE_DONATION)
        except OSError as exception:
            pass
        except:
            pass
    
    def _close_win(self, null1, null2):
        self.lock.remove()
        Gtk.main_quit()
    
    def _on_color_changed(self, null):
        tree_iter = self.cb_colors.get_active_iter()
        if tree_iter != None:
            model = self.cb_colors.get_model()
            color = model[tree_iter][:2][1]
        else:
            return
        
        if color == 'default':
            self.globalcolor.restore()
        else:
            self.globalcolor.set_color(color)


class Lock:
    """Control if Preferences is running"""
    def __init__(self):
        self.PID_FILE = '/tmp/foldercolor.pid'
    
    def remove(self):
        """Remove the lock for Preferences dialog"""
        try:
            os.remove(self.PID_FILE)
        except:
            pass
    
    def create(self):
        """Create the lock for Preferences dialog"""
        try:
            open(self.PID_FILE, 'a').close()
        except:
            pass
    
    def check(self):
        """Check if the lock exists for Preferences dialog"""
        if os.path.isfile(self.PID_FILE):
            return True
        else:
            return False


class GlobalColor:
    """Set default global color"""
    def __init__(self):
        self.foldercolor = FolderColor()
    
    def restore(self):
        """Restore theme to default"""
        path, name, index = self.foldercolor.get_current_icontheme()
        if not path:
            return
        fc_name = '.'.join([name, 'foldercolor']) # Folder Color theme
        local_theme = os.path.join(self.foldercolor.USER_PATH_THEME, fc_name)
        self._set_theme(name)
    
    def set_color(self, color):
        """Set global color"""
        path, name, index = self.foldercolor.get_current_icontheme()
        if not path:
            return
        # Read who inherits current theme
        inherit_others = self._get_inherit(index)
        if inherit_others:
            inherit = ','.join([name, inherit_others])
        else:
            inherit = name
        # Generate local theme
        parche_color = color.replace(' ', '_').lower()
        self._generate_local_theme(name, inherit, parche_color)
    
    def _get_inherit(self, index_theme):
        """Returns what theme is inherinting"""
        cfg = ConfigParser.ConfigParser()  
        cfg.read(index_theme)
        for section in cfg.sections():
            if cfg.has_option(section, 'Inherits'):
                return cfg.get(section, 'Inherits')
        return ''
    
    def _cp_icon(self, src_file, dst_file):
        try:
            shutil.copy2(src_file, dst_file)
        except:
            pass
    
    def _generate_local_theme(self, name, inherit, color):
        """Generate a inherit local theme from system theme"""
        # Create folder
        name = '.'.join([name, 'foldercolor']) # Generate a Folder Color theme
        try:
            for resolution,resolution_x in self.foldercolor.ICON_RESOLUTIONS.iteritems():
                dst_path = os.path.join(self.foldercolor.USER_PATH_THEME, name, resolution_x, 'places')
                if not os.path.exists(dst_path):
                    os.makedirs(dst_path)
        except OSError as exception:
            pass
        except:
            pass
        
        # Generate regular icons
        for folder in self.foldercolor.DEFAULT_FOLDERS:
            for resolution,resolution_x in self.foldercolor.ICON_RESOLUTIONS.iteritems():
                # Get source default icon for a resolution
                src_file = ''.join([self.foldercolor.get_path('places', resolution), self.foldercolor.get_iconname(folder, color, 'places', resolution), '.svg'])
                # Generate
                dst_file = os.path.join(self.foldercolor.USER_PATH_THEME, name, resolution_x, 'places', self._get_folder_icon(folder))
                self._cp_icon(src_file, dst_file)
        
        # Generate no regular icons: default, home, remote
        for resolution,resolution_x in self.foldercolor.ICON_RESOLUTIONS.iteritems():
            src_file = ''.join([self.foldercolor.get_path('places', resolution), self.foldercolor.get_iconname('', color, 'places', resolution), '.svg'])
            
            # folder.svg & inode-directory.svg
            dst_file = os.path.join(self.foldercolor.USER_PATH_THEME, name, resolution_x, 'places', self._get_folder_icon(None, 0)) # folder.svg
            self._cp_icon(src_file, dst_file)
            dst_file = os.path.join(self.foldercolor.USER_PATH_THEME, name, resolution_x, 'places', self._get_folder_icon(None, 1)) # inode-directory.svg
            self._cp_icon(src_file, dst_file)
            
            # user-home.svg & folder_home.svg
            src_icon_default_folder = src_file
            # Exist home? If not > default folder icon
            src_file = ''.join([self.foldercolor.get_path('places', resolution), self.foldercolor.EXTRA_HOME % color, '.svg'])
            if not os.path.isfile(src_file):
                src_file = src_icon_default_folder
            # Generate
            dst_file = os.path.join(self.foldercolor.USER_PATH_THEME, name, resolution_x, 'places', self._get_folder_icon(None, 2)) # user-home.svg
            self._cp_icon(src_file, dst_file)
            dst_file = os.path.join(self.foldercolor.USER_PATH_THEME, name, resolution_x, 'places', self._get_folder_icon(None, 3)) # folder_home.svg
            self._cp_icon(src_file, dst_file)
        
            # network-workgroup.svg & folder-remote.svg
            # Exist remote? If not > default folder icon
            src_file = ''.join([self.foldercolor.get_path('places', resolution), self.foldercolor.EXTRA_REMOTE % color, '.svg'])
            if not os.path.isfile(src_file):
                src_file = src_icon_default_folder
            # Generate
            dst_file = os.path.join(self.foldercolor.USER_PATH_THEME, name, resolution_x, 'places', self._get_folder_icon(None, 4)) # network-workgroup.svg
            self._cp_icon(src_file, dst_file)
            dst_file = os.path.join(self.foldercolor.USER_PATH_THEME, name, resolution_x, 'places', self._get_folder_icon(None, 5)) # folder-remote.svg
            self._cp_icon(src_file, dst_file)
            
            # document-open-recent.svg
            src_file = ''.join([self.foldercolor.get_path('places', resolution), self.foldercolor.EXTRA_RECENT % color, '.svg'])
            if not os.path.isfile(src_file):
                src_file = src_icon_default_folder
            # Generate
            dst_file = os.path.join(self.foldercolor.USER_PATH_THEME, name, resolution_x, 'places', self._get_folder_icon(None, 6)) # document-open-recent.svg
            self._cp_icon(src_file, dst_file)
        
        # Generate index.theme
        index_file = '/'.join([os.path.join(self.foldercolor.USER_PATH_THEME, name), 'index.theme'])
        cfg = ConfigParser.ConfigParser()
        cfg.optionxform = str
        cfg.add_section('Icon Theme')
        cfg.set('Icon Theme', 'Name',     name)
        cfg.set('Icon Theme', 'Hidden',   'true')
        cfg.set('Icon Theme', 'Comment',  'Generated by Folder Color')
        cfg.set('Icon Theme', 'Inherits', inherit)
        
        for resolution,resolution_x in self.foldercolor.ICON_RESOLUTIONS.iteritems():
            section = '/'.join([resolution_x, 'places']) # 16x16/places
            try:
                all_px = ','.join([all_px, section])
            except:
                all_px = section
        cfg.set('Icon Theme', 'Directories', all_px)
        
        for resolution,resolution_x in self.foldercolor.ICON_RESOLUTIONS.iteritems():
            section = '/'.join([resolution_x, 'places']) # 16x16/places
            cfg.add_section(section)
            cfg.set(section, 'Size',    resolution)
            cfg.set(section, 'Context', 'Places')
            cfg.set(section, 'Type',    'Threshold')
        
        f = open(index_file, 'w')
        cfg.write(f)  
        f.close()
        
        # Reload icon cache
        self._run_cmd(['gtk-update-icon-cache', '-q', os.path.join(self.foldercolor.USER_PATH_THEME, name)])
        
        # Set new local theme
        self._set_theme(name)
    
    def _run_cmd(self, cmd): # Not necesary a reply
        try:
            proc = subprocess.Popen(cmd, shell=False)
            proc.communicate()
        except:
            pass
    
    def _get_folder_icon(self, folder=None, special=0):
        """Compose icon by default"""
        # Need hacks
        if folder == None:
            if special == 6:
                iconname = 'document-open-recent.svg'
            elif special == 5:
                iconname = 'folder-remote.svg'
            elif special == 4:
                iconname = 'network-workgroup.svg'
            elif special == 3:
                iconname = 'folder_home.svg'
            elif special == 2:
                iconname = 'user-home.svg'
            elif special == 1:
                iconname = 'inode-directory.svg'
            else:
                iconname = 'folder.svg'
        elif self.foldercolor.DEFAULT_FOLDERS[folder] == self.foldercolor.DOWNLOADS:
            iconname = 'folder-download.svg'
        elif self.foldercolor.DEFAULT_FOLDERS[folder] == self.foldercolor.PUBLIC:
            iconname = 'folder-publicshare.svg'
        elif self.foldercolor.DEFAULT_FOLDERS[folder] == self.foldercolor.DESKTOP:
            iconname = 'user-desktop.svg'
        else:
            iconname = ''.join([self.foldercolor.FOLDER, '-', self.foldercolor.DEFAULT_FOLDERS[folder], '.svg'])
        return iconname
    
    def _set_theme(self, theme):
        theme_aux = '"' + theme + '"'
        self._run_cmd(['gsettings', 'set', 'org.gnome.desktop.interface', 'icon-theme', theme_aux])
        # XFCE
        self._run_cmd(['xfconf-query', '-c', 'xsettings', '-p', '/Net/IconThemeName', '-s', theme_aux])
        # MATE
        self._run_cmd(['gsettings', 'set', 'org.mate.interface', 'icon-theme', theme_aux])
        # cinnamon
        self._run_cmd(['gsettings', 'set', 'org.cinnamon.desktop.interface', 'icon-theme', theme_aux])