~deejay1/groundcontrol/fix-for-517605

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
#
# Copyright 2009 Martin Owens
#
# This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>
#
"""
Small app for selecting launchpad projects
"""

# Import standard python libs
import os
import gtk
import gtk.gdk
import pango
import logging

# Various required variables and locations
from GroundControl.gtkviews import (
    GtkApp, ThreadedWindow,
    IconManager, TreeView
)
from GroundControl.launchpad import LaunchpadProjects, get_launchpad

project_icons = IconManager('project')
ITEM_MARKUP = """<b><big>%s</big></b>
%s
  <small><i>lp:%s</i></small>"""

from shutil import copyfile
from moxml.config import newConfig, Config
from bzrlib import transport, bzrdir


class Project(object):
    """Simple object for managing a project directory"""
    def __init__(self, path, make_from=None):
        self._path   = path
        self._make   = make_from
        self._config = None
        logging.debug("Loaded project %s" % self.pid)

    @property
    def config(self):
        """Load a configuration file"""
        if not self._config:
            cfile = os.path.join(self._path, '.project')
            if os.path.isdir(self._path) and os.path.exists(cfile):
                self._config = Config(cfile)
            elif self._make:
                self._config = self.create_project(self._make)
            else:
                raise IOError("Can't find project configuration file")
        return self._config

    @property
    def pid(self):
        """Return a project id (nickname)"""
        return str(self.config['id'])

    @property
    def name(self):
        """Return a project name (with spaces)"""
        return str(self.config['name'])

    def logo(self):
        """Return the prospective logo filename"""
        return os.path.join(self._path, '.logo.png')

    def create_project(self, project):
        """Create the selected project"""
        self._path = os.path.join(self._path, project.id)
        if not os.path.exists(self._path):
            to_transport = transport.get_transport(self._path)
            to_transport.ensure_base()
            repo_format = bzrdir.format_registry.make_bzrdir('default')
            newdir = repo_format.initialize_on_transport(to_transport)
            repo = newdir.create_repository(shared=True)
            repo.set_make_working_trees(True)
            filename = os.path.join(self._path, '.project')
            pconf = newConfig( {}, filename)
            pconf['id'] = project.id
            pconf['name'] = project.name
            pconf['desc'] = project.desc
            pconf.save()
            self._save_image(project, "brand")
            self._save_image(project, "logo")
            self._save_image(project, "icon")
            return pconf

    def _save_image(self, project, name):
        """Save images to the disk as required"""
        filename = os.path.join( self._path, ".%s.png" % name )
        result = project._image_file(name)
        if result:
            copyfile( result, filename )
        else:
            logging.debug("Not saving image %s, doesn't exist." % name)


class SelectionWindow(ThreadedWindow):
    """Select a project to import."""
    name = 'project_search'

    def load(self, path, *args, **kwargs):
        """Load the project selection GUI"""
        self.slist      = None
        self.child      = None
        self._path      = path
        self._selected  = None
        self._launchpad = None
        # Setup the list of projects from a search
        self.unselected()
        self.slist = ProjectsView(self.widget('projectslist'),
            selected=self.selected,
            unselected=self.unselected)
        super(SelectionWindow, self).load(*args, **kwargs)

    @property
    def launchpad(self):
        """Return a launchpad object"""
        if not self._launchpad:
            self._launchpad = get_launchpad()
        return self._launchpad

    def inital_thread(self):
        """What to run when we execute the thread."""
        # Set up the launchpad projects object and connect search
        self.lpp = LaunchpadProjects(self.launchpad.launchpad)
        self.lpp.connect_signal("search_finish", self.call, 'finish_search')
        self.lpp.connect_signal("search_result", self.call, 'add_search_item')
        self.call('finish_search')

    def add_search_item(self, item):
        """Add an item to the slist"""
        return self.slist.add_item(item)

    def signals(self):
        """project window signals"""
        return {
            'search' : self.project_search,
        }

    def get_args(self):
        """Return the selected project"""
        return {
            'project' : self.selected(),
        }

    def selected(self, item=None):
        """An item has surely been selected."""
        if item:
            self._selected = item
            self.widget('buttonok').set_sensitive(True)
        return self._selected

    def unselected(self):
        """All items unselected"""
        self._selected = None
        self.widget('buttonok').set_sensitive(False)

    def project_search(self, button=None):
        """Search for projects in launchpad."""
        self.slist.clear()
        self.widget("findButton").hide()
        self.widget("term").hide()
        self.widget("searchLabel").set_text(
            _("Searching Launchpad... Please Wait"))
        result = self.widget("term").get_text()
        #Trad: Thread(target=self.lpp.search, args=(result))
        self.start_thread(self.lpp.search, result)
        #Old: self.lpp.search(result)

    def finish_search(self, widget=None):
        """Event of finishing the search process."""
        self.widget("findButton").show()
        self.widget("term").show()
        self.widget("searchLabel").set_text("Name:")

    def is_valid(self):
        """Return true is a project is selected"""
        return self._selected != None


class ProjectSelection(GtkApp):
    """Application for loading a project"""
    gtkfile = 'project-select.glade'
    windows = [ SelectionWindow ]


class ProjectsView(TreeView):
    """Controls and operates a table as a projects view."""
    def setup(self):
        """Setup a treeview for showing services"""
        def text_cell_func(cell_layout, renderer, model, item_iter):
            """Render the text of the services tree view"""
            item = model.get_value(item_iter, 0)
            name = str(item.name).replace('&', '&amp;')
            desc = str(item.desc).replace('&', '&amp;')
            markup = ITEM_MARKUP % (name, desc, item.id)
            renderer.set_property("markup", markup)

        def icon_cell_func(column, cell, model, item_iter):
            """Reender the icons of the services tree view"""
            item = model.get_value(item_iter, 0)
            img = project_icons.get_icon(item.logo())
            img2 = img.scale_simple(64, 64, gtk.gdk.INTERP_BILINEAR)
            cell.set_property("pixbuf", img2)
            cell.set_property("visible", True)

        svlist = super(ProjectsView, self).setup()
        column = gtk.TreeViewColumn((_("Online Projects")))
        column.set_sizing(gtk.TREE_VIEW_COLUMN_AUTOSIZE)
        #column.set_sizing(gtk.TREE_VIEW_COLUMN_FIXED)
        column.set_expand(True)
        # The icon
        renderer_icon = gtk.CellRendererPixbuf()
        renderer_icon.set_property("ypad", 8)
        renderer_icon.set_property("xpad", 8)
        column.pack_start(renderer_icon, False)
        column.set_cell_data_func(renderer_icon, icon_cell_func)
        # The name
        renderer = gtk.CellRendererText()
        renderer.props.wrap_width = 660
        renderer.props.wrap_mode = pango.WRAP_WORD
        column.pack_start(renderer, True)
        column.set_cell_data_func(renderer, text_cell_func)
        # Add the required coluns to the treeview
        svlist.append_column(column)