Source

pida-main / pida / services / window / window.py

  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
# -*- coding: utf-8 -*-
"""
    :copyright: 2005-2008 by The PIDA Project
    :license: GPL 2 or later (see README/COPYING/LICENSE)
"""

import gtk
import string
from functools import partial

# PIDA Imports
from pida.core.service import Service
from pida.core.commands import CommandsConfig
from pida.core.events import EventsConfig
from pida.core.options import OptionsConfig, Color
from pida.core.actions import ActionsConfig, global_accelerator_group
from pida.core.document import Document
from pida.core.environment import workspace_name, settings_dir
from pida.utils import json

from pida.ui.actions import PidaMenuToolAction, PidaRememberToggle

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


def window_config():
    return settings_dir()/'window_extra_window-config.json'

def load_window_config():
    return json.load(window_config(), fallback={})




class ActionWindowMapping(list):
    """
    Specialised mapping for persitant shortcuts on plugin windows
    """
    def __init__(self, svc):
        self.svc = svc
        super(ActionWindowMapping, self).__init__()


    def add(self, config):
        """
        Add a new shortcut for focusing a window.
        Get the shorcut from the window-config
        """
        self.append(config)
        keya = config.key
        curshort = load_window_config().get(keya, '')

        act = self.svc.actions.create_action(
            keya,
            gtk.Action,
            "Focus %s" %_(config.label_text),
            config.description or _('Focus %s window') %_(config.label_text),
            "",
            self.svc.actions.on_focus_window,
            config.default_shortcut,
            global_=True
        )
        act.key = config.key
        act.visible_action = config.action
        self._actions[config.key] = act
        self.svc.actions.set_value(keya, curshort)
        # make the shortcuts update to reflect change
        self.svc.boss.get_service('shortcuts').update()

    def remove(self, config):
        """Unregister a WindowConfig"""
        # unregister action
        self.svc.actions.remove_action(self._actions[config.key])
        del self._actions[config.key]
        #self.remove(config)
        self.svc.boss.get_service('shortcuts').update()


class WindowCommandsConfig(CommandsConfig):

    def add_view(self, paned, view, removable=True, present=True, detachable=True):
        self.svc.window.add_view(paned, view, removable, present, detachable=detachable)
        self.svc.save_state()

    def add_detached_view(self, paned, view, size=(500,400)):
        self.add_view(paned, view)
        self.detach_view(view, size)
        self.svc.save_state()

    def close_focus_pane(self):
        pane = self.svc.window.get_focus_pane()
        if pane:
            if pane.view.can_be_closed() and pane.view:
                self.remove_view(pane.view)

    def toggle_sticky_pane(self):
        pane = self.svc.window.get_focus_pane()
        if pane:
            self.svc.window.paned.set_params(
                    pane, 
                    keep_on_top=not pane.get_params().keep_on_top)

    def remove_view(self, view):
        self.svc.window.remove_view(view)
        self.svc.save_state()

    def detach_view(self, view, size):
        self.svc.window.detach_view(view, size)
        self.svc.save_state()

    def present_view(self, view):
        self.svc.window.present_view(view)
        self.svc.save_state()

    def is_added(self, view):
        return view in self.svc.window

class WindowActionsConfig(ActionsConfig):


    actions = [
        gtk.ToggleAction('show_toolbar',
            _('Show Toolbar'),
            _('Toggle the visible state of the toolbar'),
            'face-glasses'),
        gtk.ToggleAction('show_menubar',
            _('Show _Menubar'),
            _('Toggle the visible state of the menubar'),
            'face-glasses'),
        gtk.ToggleAction('fullscreen',
            _('F_ullscreen'),
            _('Toggle the fullscreen mode'),
            gtk.STOCK_FULLSCREEN),
        gtk.ToggleAction('max_editor',
            _('M_aximize Editor'),
            _('Maximizes the editor by hiding panels'),
            gtk.STOCK_FULLSCREEN),
        gtk.Action('switch_next_term',
            _('Next _terminal'),
            _('Switch to the next terminal'),
            gtk.STOCK_GO_FORWARD),
        gtk.Action('switch_prev_term',
            _('Previous te_rminal'),
            _('Switch to the previous terminal'),
            gtk.STOCK_GO_BACK),
        gtk.Action('focus_terminal',
            _('F_ocus terminal'),
            _('Focus terminal pane terminal'),
            'terminal'),
        gtk.Action('close_pane',
            _('Close Pane'),
            _('Close the current active pane'),
            gtk.STOCK_CLOSE),
        gtk.Action('toggle_sticky',
            _('Toggle sticky'),
            _('Toggle the sticky button on current pane'),
            'pin'),
        PidaMenuToolAction('WindowMenu',
            _('Win_dows'),
            _('Show window list'),
            'package_utilities'),
    ]

    accels = {
        'show_toolbar': '<Shift><Control>l',
        'show_menubar': '<Shift><Control>u',
        'fullscreen': '<Shift>F11',
        'max_editor': 'F11',
    }

    global_accels = {
        'switch_next_term': '<Alt>Right',
        'switch_prev_term': '<Alt>Left',
        'focus_terminal': '<Shift><Control>i',
        'close_pane': '<Control>F4',
        'toggle_sticky': '',
    }

    def on_focus_window(self, action):
        if action.visible_action and \
           isinstance(action.visible_action, gtk.ToggleAction):
                action.visible_action.set_active(True)
        self.svc.present_key_window(action.key)

    def on_WindowMenu(self, action):
        self.svc.create_window_list()

    def on_focus_terminal(self, action):
        self.svc.window.present_paned('Terminal')

    def on_switch_next_term(self, action):
        self.svc.window.switch_next_view('Terminal')

    def on_switch_prev_term(self, action):
        self.svc.window.switch_prev_view('Terminal')

    def on_close_pane(self, action):
        self.svc.cmd('close_focus_pane')

    def on_toggle_sticky(self, action):
        self.svc.cmd('toggle_sticky_pane')

    def on_fullscreen(self, action):
        self.svc.set_fullscreen(action.get_active())

    def on_max_editor(self, action):
        self.svc.set_max_editor(action.get_active())

    def on_show_ui(self, action):
        val = action.get_active()
        self.svc.set_opt(action.get_name(), val)
        getattr(self.svc, action.get_name())(val)


class WindowEvents(EventsConfig):

    def subscribe_all_foreign(self):
        self.subscribe_foreign('buffer', 'document-changed',
            self.on_document_changed)
        self.subscribe_foreign('editor', 'started',
            self.on_editor_started)

    def on_document_changed(self, document):
        self.svc.update_title(document=document)

    def on_editor_started(self):
        self.svc.boss.hide_splash()
        self.svc.window.show()




class WindowOptionsConfig(OptionsConfig):

    def create_options(self):
        self.create_option(
            'show_toolbar',
            _('Show the toolbar'),
            bool,
            True,
            _('Whether the main toolbar will be shown'),
            self.on_show_ui,
        )

        self.create_option(
            'show_menubar',
            _('Show the menubar'),
            bool,
            True,
            _('Whether the main menubar will be shown'),
            self.on_show_ui,
        )

        self.create_option(
            'window_title',
            _('Window title'),
            str,
            'Pida - $workspace - $filepath',
            _('Title template for the pida window.\n'
              '$basename : Filename of Document - $filepath : Full filepath \n'
              '$directory : Directory if file - $workspace : Workspace name \n'
              '$project_path - $project_name'),
            self.on_title_change,
        )

        self.create_option(
            'project_color',
            _('Project color'),
            Color,
            '#600060',
            _('The color projects shall have in PIDA'),
        )

        self.create_option(
            'no_project_color',
            _('No project color'),
            Color,
            '#CB4444',
            _('The color projects shall have in PIDA'),
        )

        self.create_option(
            'directory_color',
            _('Directory color'),
            Color,
            '#0000c0',
            _('The color directories shall have in PIDA'),
        )

    def on_show_ui(self, option):
        self.svc.get_action(option.name).set_active(option.value)

    def on_title_change(self, *args):
        self.svc._title_template = None
        self.svc.update_title()

# Service class
class Window(Service):
    """The PIDA Window Manager"""

    commands_config = WindowCommandsConfig
    options_config = WindowOptionsConfig
    actions_config = WindowActionsConfig
    events_config = WindowEvents

    def pre_start(self):
        self._title_template = None
        self._last_focus = None
        super(Window, self).pre_start()
        self.restore_state(pre=True)

    @property
    def state_config(self):
        return settings_dir().join('workspaces', workspace_name(), "window.state.json")

    def start(self):
        # Explicitly add the permanent views
        for service in ['project', 'filemanager', 'buffer']:
            view = self.boss.cmd(service, 'get_view')
            self.cmd('add_view', paned='Buffer', view=view, removable=False, present=False)
        self._fix_visibilities()
        self._window_list_id = self.boss.window.create_merge_id()
        self._action_group = gtk.ActionGroup('window_list')
        self.boss.window._uim._uim.insert_action_group(self._action_group, -1)
        self.restore_state()
        self.window.paned.connect('config-changed', self.save_state)
        self.window.paned.connect('pane-attachment-changed', self._on_pane_detachment)

    def pre_stop(self):
        self.save_state()
        return True

    def stop(self):
        self.save_state()

    def restore_state(self, pre=False):
        try:
            data = json.load(self.state_config)
        except:
            self.log.warning("Can't open window state file {config}",
                             config=self.state_config)
            return

        if pre:
            # in pre mode we restore the paned config and the window position/size, etc
            self.boss.window.paned.set_config(data.get('panedstate', ''))
            # restore window size and position
            if data.has_key('pida_main_window'):
                cdata = data['pida_main_window']
                # test if data is valid. we don't place the window where it
                # is not fully visible
                try:
                    height = max(int(cdata['height']), 100)
                    width = max(int(cdata['width']), 100)
                    x = max(int(cdata['x']), 0)
                    y = max(int(cdata['y']), 0)
                    if x + width <= gtk.gdk.screen_width() and \
                       y + height <= gtk.gdk.screen_height():
                        self.boss.window.resize(width, height)
                        self.boss.window.move(x, y)
                    else:
                        self.log.debug("Won't restore window size outside screen")
                except (ValueError, KeyError):
                    pass
            return

        for service in self.boss.get_services():
            name = service.get_name()
            info = data.get(name, {})

            if not info:
                continue
            for action in service.actions.list_actions():
                if isinstance(action, PidaRememberToggle):
                    if action.get_name() in info:
                        action.set_active(data[name][action.get_name()])

    def save_state(self, *args):
        if not self.started:
            return
        data = {}
        data['panedstate'] = self.boss.window.paned.get_config()
        # save window size and position
        size = self.boss.window.get_size()
        pos = self.boss.window.get_position()
        data['pida_main_window'] = {
            "width": size[0],
            "height": size[1],
            "x": pos[0],
            "y": pos[1],
        }
        for service in self.boss.get_services():
            cur = {}
            if not hasattr(service, "actions"):
                continue
            for action in service.actions.list_actions():
                if isinstance(action, PidaRememberToggle):
                    cur[action.get_name()] = action.props.active
            if cur:
                data[service.get_name()] = cur
        
        try:
            json.dump(data, self.state_config)
        except:
            self.log.warning("Can't open state file {config}",
                             config=self.state_config)

    def _on_pane_detachment(self, bigpaned, pane, detached):
        if detached:
            # thanks gtk for not letting me test if accel is already added
            win = pane.get_child().get_toplevel()
            if not getattr(win, '_pida_accel_added', False):
                win.add_accel_group(global_accelerator_group)
                win._pida_accel_added = True

    def update_title(self, document=None):
        if self._title_template is None:
            self._title_template = string.Template(self.opt('window_title'))
        if document is None:
            document = self.boss.cmd('buffer', 'get_current')
        
        subs = {'basename': document.basename or _('New Document'),
                'filepath': document.filename or _('New Document'),
                'directory': document.directory or '',
                'workspace': workspace_name(),
                'project_path': document.project and document.project.data_dir or '',
                'project_name': document.project_name
               }
        
        self.window.set_title(self._title_template.safe_substitute(subs))
        

    def _fix_visibilities(self):
        for name in ['show_toolbar', 'show_menubar']:
            val = self.opt(name)
            self.get_action(name).set_active(val)
            getattr(self, name)(val)

    def show_toolbar(self, visibility):
        self.window.set_toolbar_visibility(visibility)

    def show_menubar(self, visibility):
        self.window.set_menubar_visibility(visibility)

    def set_fullscreen(self, var):
        if var:
            self.boss.window.fullscreen()
        else:
            self.window.unfullscreen()


    def set_max_editor(self, var):
        if var:
            # shall we do a weak ref here ?
            self._last_focus = self.boss.window.get_focus()
            self.window.set_fullscreen(var)
            self.boss.editor.cmd('grab_focus')
        else:
            self.window.set_fullscreen(var)
            if self._last_focus:
                try:
                    # this maight fail due various reasons, like
                    # the window was destroyed etc
                    self._last_focus.grab_focus()
                except: 
                    pass

    def get_fullscreen(self, var):
        return self.window.get_fullscreen()

    def _on_window_action(self, action, view):
        self.boss.window.present_view(view)

    def _on_doc_action(self, action, doc):
        self.boss.get_service('buffer').view_document(doc)

    def present_key_window(self, key):
        for pane in self.boss.window.paned.list_panes(every=True):
            if pane.key == key:
                self.cmd('present_view', view=pane)
                return

    def create_window_list(self):
        # update the window menu list
        # clean up the old list
        if not self.started:
            return
        self.boss.window.remove_uidef(self._window_list_id)
        for action in self._action_group.list_actions():
            self._action_group.remove_action(action)

        # add panels to list. they are sorted after the paned positions and
        # therefor good
        panes = self.boss.window.paned.list_panes(every=True)
        for i, pane in enumerate(panes):
            action_name = "show_window_%s" %i
            act = gtk.Action(action_name,
                "_%s" %pane.label_text,
                '',
                '')
            act.connect('activate', self._on_window_action, pane)
            self._action_group.add_action(act)
            self.boss.window._uim._uim.add_ui(
                self._window_list_id,
                "ui/menubar/AddMenu/WindowMenu/window_list", 
                "_%s" %pane.label_text, 
                action_name, 
                gtk.UI_MANAGER_MENUITEM, 
                False)            #mi = act.create_menu_item()
            i += 1
        # add documents to list
        docs = list(self.boss.get_service('buffer').get_documents().itervalues())
        # we sort the docs list alphabeticly as its easier for the eye to navigate
        docs.sort(key=lambda x:unicode(x).lower())
        for i, doc in enumerate(docs):
            action_name = "show_document_%s" %i
            act = gtk.Action(action_name,
                unicode(doc),
                '',
                '')
            act.connect('activate', self._on_doc_action, doc)
            self._action_group.add_action(act)
            self.boss.window._uim._uim.add_ui(
                self._window_list_id,
                "ui/menubar/AddMenu/WindowMenu/buffer_list", 
                unicode(doc), 
                action_name, 
                gtk.UI_MANAGER_MENUITEM, 
                False)
            i += 1
        self.boss.window._uim.ensure_update()
        return None

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