def __init__(self, blink_contact):
        NSBundle.loadNibNamed_owner_("Contact", self)
        self.window.setTitle_(NSLocalizedString("Edit Contact",
                                                "Window title"))
        self.addButton.setTitle_(NSLocalizedString("OK", "Button title"))
        self.dealloc_timer = None

        self.blink_contact = blink_contact
        self.belonging_groups = self.model.getBlinkGroupsForBlinkContact(
            blink_contact)
        self.all_groups = [
            g for g in self.groupsList if g.group is not None
            and not isinstance(g.group, VirtualGroup) and g.add_contact_allowed
        ]
        self.nameText.setStringValue_(blink_contact.name or "")
        key = NSLocalizedString(
            "Public key: %s", "Label"
        ) % blink_contact.contact.public_key_checksum if blink_contact.contact.public_key_checksum else ''
        self.publicKey.setStringValue_(key)
        self.organizationText.setStringValue_(blink_contact.organization or "")
        self.photoImage.setImage_(blink_contact.icon)
        self.preferred_media = blink_contact.preferred_media
        address_types = list(
            item.title() for item in self.addressTypesPopUpButton.itemArray())
        for item in blink_contact.contact.uris:
            type = format_uri_type(item.type)
            if type not in address_types:
                self.addressTypesPopUpButton.addItemWithTitle_(type)

        self.addButton.setEnabled_(
            True if blink_contact.contact.uris else False)
        self.default_uri = self.blink_contact.contact.uris.default
        self.autoanswerCheckbox.setState_(
            NSOnState if blink_contact.auto_answer else NSOffState)

        self.uris = sorted(blink_contact.contact.uris,
                           key=lambda uri: uri.position
                           if uri.position is not None else sys.maxsize)
        # TODO: how to handle xmmp: uris?
        #for uri in self.uris:
        #if uri.type is not None and uri.type.lower() == 'xmpp' and ';xmpp' in uri.uri:
        #    uri.uri = uri.uri.replace(';xmpp', '')

        self.update_default_uri()
        self.addressTable.reloadData()

        self.subscriptions = {
            'presence': {
                'subscribe': blink_contact.contact.presence.subscribe,
                'policy': blink_contact.contact.presence.policy
            },
            'dialog': {
                'subscribe': blink_contact.contact.dialog.subscribe,
                'policy': blink_contact.contact.dialog.policy
            }
        }
        self.defaultButton.setEnabled_(False)
        self.updateSubscriptionMenus()
        self.updatePreferredMediaMenus()
        self.loadGroupNames()
    def rightMouseDown_(self, event):
        point = self.window().convertScreenToBase_(NSEvent.mouseLocation())
        event = NSEvent.mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure_(
                  NSRightMouseUp, point, 0, NSDate.timeIntervalSinceReferenceDate(), self.window().windowNumber(),
                  self.window().graphicsContext(), 0, 1, 0)

        videoDevicesMenu = NSMenu.alloc().init()
        lastItem = videoDevicesMenu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Select Video Camera", "Menu item"), "", "")
        lastItem.setEnabled_(False)
        videoDevicesMenu.addItem_(NSMenuItem.separatorItem())

        i = 0
        for item in Engine().video_devices:
            if item not in (None, 'system_default'):
                i += 1

            lastItem = videoDevicesMenu.addItemWithTitle_action_keyEquivalent_(item, "changeVideoDevice:", "")
            lastItem.setRepresentedObject_(item)
            if SIPApplication.video_device.real_name == item:
                lastItem.setState_(NSOnState)

        if i > 1:
              videoDevicesMenu.addItem_(NSMenuItem.separatorItem())
              settings = SIPSimpleSettings()
              lastItem = videoDevicesMenu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Auto Rotate Cameras", "Menu item"), "toggleAutoRotate:", "")
              lastItem.setState_(NSOnState if settings.video.auto_rotate_cameras else NSOffState)

        NSMenu.popUpContextMenu_withEvent_forView_(videoDevicesMenu, event, self.window().contentView())
Exemple #3
0
def addDetailSidebarLabels(page):
    '''adds localized labels for the detail view sidebars'''
    page['informationLabel'] = NSLocalizedString(
                                    u"Information",
                                    u"Sidebar Information label")
    page['categoryLabel'] = NSLocalizedString(
                                    u"Category:",
                                    u"Sidebar Category label")
    page['versionLabel'] = NSLocalizedString(
                                    u"Version:",
                                    u"Sidebar Version label")
    page['sizeLabel'] = NSLocalizedString(
                                    u"Size:",
                                    u"Sidebar Size label")
    page['developerLabel'] = NSLocalizedString(
                                    u"Developer:",
                                    u"Sidebar Developer label")
    page['statusLabel'] = NSLocalizedString(
                                    u"Status:", u"Sidebar Status label")
    page['moreByDeveloperLabel'] = NSLocalizedString(
                                    u"More by %s",
                                    u"Sidebar More By Developer label")
    page['moreInCategoryLabel'] = NSLocalizedString(
                                    u"More in %s",
                                    u"Sidebar More In Category label")
    page['typeLabel'] = NSLocalizedString(
                                    u"Type:", u"Sidebar Type label")
    page['dueLabel'] = NSLocalizedString(
                                    u"Due:", u"Sidebar Due label")
    def userClickedToolbarItem_(self, sender):
        if sender.itemIdentifier() == 'smileys':
            self.chatViewController.expandSmileys = not self.chatViewController.expandSmileys
            sender.setImage_(NSImage.imageNamed_("smiley_on" if self.chatViewController.expandSmileys else "smiley_off"))
            self.chatViewController.toggleSmileys(self.chatViewController.expandSmileys)

            row = self.contactTable.selectedRow()
            if row and row > 1 and self.contacts[row].presence_contact is not None:
                self.contacts[row].presence_contact.contact.disable_smileys = not self.contacts[row].presence_contact.contact.disable_smileys
                self.contacts[row].presence_contact.contact.save()

        elif sender.itemIdentifier() == 'delete':
            if self.selectedTableView == self.contactTable:
                try:
                    row = self.contactTable.selectedRow()
                    self.showDeleteConfirmationDialog(row)
                except IndexError:
                    pass

            elif self.selectedTableView == self.indexTable:
                try:
                    row = self.indexTable.selectedRow()
                    local_uri = self.dayly_entries[row].objectForKey_("local_uri")
                    remote_uri = self.dayly_entries[row].objectForKey_("remote_uri")
                    remote_uri_sql = self.dayly_entries[row].objectForKey_("remote_uri_sql")
                    date = self.dayly_entries[row].objectForKey_("date")
                    media_type = self.dayly_entries[row].objectForKey_("type")

                    label = NSLocalizedString("Please confirm the deletion of %s history entries", "Label") % media_type + NSLocalizedString(" from %s", "SIP Address label") % remote_uri + NSLocalizedString(" on %s. ", "Date label") % date + NSLocalizedString("This operation cannot be undone. ", "Label")
                    ret = NSRunAlertPanel(NSLocalizedString("Purge History Entries", "Window title"), label, NSLocalizedString("Confirm", "Button title"), NSLocalizedString("Cancel", "Button title"), None)
                    if ret == NSAlertDefaultReturn:
                        self.delete_messages(local_uri=local_uri, remote_uri=remote_uri_sql, media_type=media_type, date=date)
                except IndexError:
                    pass
Exemple #5
0
    def cropAndAddImage(self, path):
        try:
            image = NSImage.alloc().initWithContentsOfFile_(path)
        except:
            NSRunAlertPanel(
                NSLocalizedString("Camera Capture Error", "Window title"),
                NSLocalizedString("%s is not a valid image", "Label") % path,
                NSLocalizedString("OK", "Button title"), None, None)
            return

        rect = NSZeroRect.copy()
        rect.size = image.size()
        curSize = self.cropWindow.frame().size
        if rect.size.width > curSize.width or rect.size.height > curSize.height:
            self.cropWindowImage.setFrame_(rect)
        self.cropOriginalImage = image.copy()
        self.cropWindowImage.setImage_(image)

        if NSApp.runModalForWindow_(self.cropWindow) == NSOKButton:
            dt = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
            image = self.cropWindowImage.getCropped()

            path = self.storage_folder + "/photo%s.png" % dt
            jpg_data = NSBitmapImageRep.alloc().initWithData_(
                image.
                TIFFRepresentation()).representationUsingType_properties_(
                    NSJPEGFileType, {NSImageCompressionFactor: 0.9})
            data = jpg_data.bytes().tobytes()
            with open(path, 'wb') as f:
                f.write(data)

            self.cropWindow.orderOut_(None)
            self.refreshLibrary()
        else:
            self.cropWindow.orderOut_(None)
    def isScrolling_(self, scrollTop):
        if not self.handle_scrolling:
            return

        if self.editorVisible:
            return

        if scrollTop < 0:
            if self.scrollingTimer is None:
                self.scrollingTimer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
                    1, self, "scrollTimerDelay:", None, False)
            self.scrolling_back = True
        else:
            self.scrolling_back = False
            if self.scrollingTimer is not None:
                self.scrollingTimer.invalidate()
                self.scrollingTimer = None

            if scrollTop == 0 and self.handle_scrolling:
                current_label = self.lastMessagesLabel.stringValue()
                new_label = NSLocalizedString(
                    "Keep scrolling up for more than one second to load older messages",
                    "Label")
                if current_label != new_label and NSLocalizedString(
                        "Loading", "Label") not in current_label:
                    self.lastMessagesLabel.setStringValue_(new_label)
                NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
                    4, self, "showLastScrollLabel:", None, False)
Exemple #7
0
    def render_previous_transfers(self, transfers):
        last_displayed_item = self.listView.subviews().lastObject()

        for transfer in transfers:
            item = FileTransferItemView.alloc().initWithFrame_oldTransfer_(
                NSMakeRect(0, 0, 100, 100), transfer)
            if last_displayed_item:
                self.listView.insertItemView_before_(item, last_displayed_item)
            else:
                self.listView.addItemView_(item)

            self.listView.relayout()
            self.listView.display()
            h = self.listView.minimumHeight()
            self.listView.scrollRectToVisible_(NSMakeRect(0, h - 1, 100, 1))

        count = len(self.listView.subviews())
        if count == 1:
            self.bottomLabel.setStringValue_(
                NSLocalizedString("1 item", "Label"))
        else:
            self.bottomLabel.setStringValue_(
                NSLocalizedString("%i items", "Label") %
                count if count else "")

        self.loaded = True
    def groupPopUpButtonClicked_(self, sender):
        item = sender.selectedItem()
        index = self.groupPopUp.indexOfSelectedItem()
        if index < 2:
            return

        grp = item.representedObject()
        if grp:
            if grp in self.belonging_groups:
                self.belonging_groups.remove(grp)
            else:
                self.belonging_groups.append(grp)

        else:
            menu_item = self.groupPopUp.itemAtIndex_(index)
            if menu_item.title() == NSLocalizedString("Select All",
                                                      "Menu item"):
                self.belonging_groups = self.all_groups
            elif menu_item.title() == NSLocalizedString(
                    "Deselect All", "Menu item"):
                self.belonging_groups = []
            elif menu_item.title() == NSLocalizedString(
                    "Add Group...", "Menu item"):
                self.model.addGroup()

        self.loadGroupNames()
    def addRemoveParticipant_(self, sender):
        if sender.selectedSegment() == 0:
            participant = self.participant.stringValue().strip().lower()

            if participant and "@" not in participant and self.default_domain:
                participant = '%s@%s' % (participant, self.default_domain)

            if participant:
                participant = sip_prefix_pattern.sub("", str(participant))

            if not participant or not validateParticipant(participant):
                NSRunAlertPanel(NSLocalizedString("Add New Participant", "Window title"),
                                NSLocalizedString("Participant must be a valid SIP address. ", "Label"),
                                NSLocalizedString("OK", "Button title"),
                                None, None)
                return

            if participant not in self._participants:
                self._participants.append(participant)
                self.startWhenParticipantsAvailable.setEnabled_(True)
                self.participantsTable.reloadData()
                self.participantsTable.scrollRowToVisible_(len(self._participants)-1)
                self.participant.setStringValue_('')
        elif sender.selectedSegment() == 1:
            participant = self.selectedParticipant()
            if participant is None and self._participants:
                participant = self._participants[-1]
            if participant is not None:
                self._participants.remove(participant)
                self.startWhenParticipantsAvailable.setEnabled_(bool(len(self._participants)))
                if len(self._participants) == 0:
                    self.startWhenParticipantsAvailable.setState_(NSOffState)
                self.participantsTable.reloadData()
Exemple #10
0
    def addImageFile(self, path):
        path = os.path.normpath(path)

        if os.path.dirname(path) != self.storage_folder:
            # scale and copy the image to our photo dir
            try:
                image = NSImage.alloc().initWithContentsOfFile_(path)
            except:
                NSRunAlertPanel(
                    NSLocalizedString("Camera Capture Error", "Window title"),
                    NSLocalizedString("%s is not a valid image", "Label") %
                    path, NSLocalizedString("OK", "Button title"), None, None)
                return

            size = image.size()
            if size.width > 128 or size.height > 128:
                image.setScalesWhenResized_(True)
                image.setSize_(NSMakeSize(128, 128 * size.height / size.width))

            finalpath = self.storage_folder + "/" + os.path.basename(path)
            prefix, ext = os.path.splitext(finalpath)
            i = 0
            while os.path.exists(finalpath):
                finalpath = prefix + str(i) + ext

            image.TIFFRepresentation().writeToFile_atomically_(
                finalpath, False)
            self.refreshLibrary()
Exemple #11
0
    def _NH_BlinkFileTransferNewOutgoing(self, sender, data):
        try:
            item = next((item for item in self.listView.subviews().copy()
                         if item.file_path == sender.ft_info.file_path
                         and item.remote_uri == sender.ft_info.remote_uri))
            item.replaceWithTransfer_(sender)
            self.listView.relayout()

        except StopIteration:
            item = FileTransferItemView.alloc().initWithFrame_transfer_(
                NSMakeRect(0, 0, 100, 100), sender)
            self.listView.addItemView_(item)
            h = NSHeight(self.listView.frame())
            self.listView.scrollRectToVisible_(NSMakeRect(0, h - 1, 100, 1))

        file_path = sender.ft_info.file_path.decode() if isinstance(
            sender.ft_info.file_path, bytes) else sender.ft_info.file_path
        if 'screencapture' not in file_path:
            self.window.orderFront_(None)

        count = len(self.listView.subviews())
        if count == 1:
            self.bottomLabel.setStringValue_(
                NSLocalizedString("1 item", "Label"))
        else:
            self.bottomLabel.setStringValue_(
                NSLocalizedString("%i items", "Label") % count)
    def renderMessages(self, messages=None):
        self.chatViewController.clear()
        self.chatViewController.resetRenderedMessages()
        self.chatViewController.last_sender = None

        if messages is not None:
            # new message list. cache for pagination and reset pagination to the last page
            self.messages = list(reversed(messages))
            message_count = len(messages)
            start = message_count // MAX_MESSAGES_PER_PAGE * MAX_MESSAGES_PER_PAGE
            end = message_count
        else:
            message_count = len(self.messages)
            start = self.start
            end = min(start + MAX_MESSAGES_PER_PAGE, message_count)

        for row in self.messages[start:end]:
            self.renderMessage(row)

        self.paginationButton.setEnabled_forSegment_(start > MAX_MESSAGES_PER_PAGE, 0)
        self.paginationButton.setEnabled_forSegment_(start > 0, 1)
        self.paginationButton.setEnabled_forSegment_(start + MAX_MESSAGES_PER_PAGE + 1 < message_count, 2)
        self.paginationButton.setEnabled_forSegment_(start + MAX_MESSAGES_PER_PAGE * 2 < message_count, 3)

        if message_count == 0:
            text = NSLocalizedString("No entry found", "Label")
        elif message_count == 1:
            text = NSLocalizedString("Displaying 1 entry", "Label")
        elif message_count < MAX_MESSAGES_PER_PAGE:
            text = NSLocalizedString("Displaying {} entries".format(end), "Label")
        else:
            text = NSLocalizedString("Displaying {} to {} out of {} entries", "Label").format(start+1, end, message_count)

        self.foundMessagesLabel.setStringValue_(text)
Exemple #13
0
def addGeneralLabels(page):
    '''adds localized labels for Software, Categories, My Items and Updates to html pages'''
    page['SoftwareLabel'] = NSLocalizedString(u"Software", u"Software label")
    page['CategoriesLabel'] = NSLocalizedString(u"Categories",
                                                u"Categories label")
    page['MyItemsLabel'] = NSLocalizedString(u"My Items", u"My Items label")
    page['UpdatesLabel'] = NSLocalizedString(u"Updates", u"Updates label")
Exemple #14
0
def build_categories_page():
    '''Build page showing available categories and some items in each one'''
    all_items = MunkiItems.getOptionalInstallItems()
    header = NSLocalizedString(u"Categories", u"Categories label")
    page_name = u'categories.html'
    category_list = []
    for item in all_items:
        if 'category' in item and item['category'] not in category_list:
            category_list.append(item['category'])

    item_html = build_category_items_html()

    all_categories_label = NSLocalizedString(u"All Categories",
                                             u"AllCategoriesLabel")
    categories_html = u'<option selected>%s</option>\n' % all_categories_label
    for item in sorted(category_list):
        categories_html += u'<option>%s</option>\n' % item

    page = {}
    page['list_items'] = item_html
    page['category_items'] = categories_html
    page['header_text'] = header

    footer = get_template('footer_template.html', raw=True)
    generate_page(page_name,
                  'list_template.html',
                  page,
                  showcase=u'',
                  sidebar=u'',
                  footer=footer)
    def open(self):
        self.sasLabel.setStringValue_(
            self.stream.encryption.zrtp.sas.decode().upper())
        self.cipherLabel.setStringValue_(
            NSLocalizedString("Encrypted using %s", "Label") %
            self.stream.encryption.cipher)
        if self.streamController.sessionController.remote_focus:
            self.peerName.setEnabled_(False)
            self.peerName.setStringValue_(
                self.streamController.sessionController.titleShort)
        else:
            if self.stream.encryption.zrtp.peer_name:
                self.peerName.setStringValue_(
                    self.stream.encryption.zrtp.peer_name)
            else:
                self.peerName.setStringValue_(
                    self.streamController.sessionController.titleShort)

        self.window.setTitle_(
            NSLocalizedString("ZRTP with %s", "Label") %
            self.streamController.sessionController.remoteAOR)

        self.validateButton.setTitle_(
            NSLocalizedString("Invalidate", "Label") if self.stream.encryption.
            zrtp.verified else NSLocalizedString("Validate", "Label"))

        self.window.makeKeyAndOrderFront_(self.validateButton)
    def changeStatus(self, newstate, fail_reason=None):
        if self.status == newstate:
            return

        self.status = newstate
        MediaStream.changeStatus(self, newstate, fail_reason)

        if newstate in (STREAM_IDLE, STREAM_FAILED):
            self.end()
            if self.videoWindowController and self.videoWindowController.localVideoWindow:
                self.videoWindowController.localVideoWindow.cancelButton.setHidden_(
                    True)

        if self.videoWindowController:
            if newstate == STREAM_WAITING_DNS_LOOKUP:
                self.videoWindowController.showStatusLabel(
                    NSLocalizedString("Finding Destination...",
                                      "Audio status label"))
            elif newstate == STREAM_RINGING:
                self.videoWindowController.showStatusLabel(
                    NSLocalizedString("Ringing...", "Audio status label"))
            elif newstate == STREAM_CONNECTING:
                self.videoWindowController.showStatusLabel(
                    NSLocalizedString("Connecting...", "Audio status label"))
            elif newstate == STREAM_CONNECTED:
                if not self.media_received:
                    self.videoWindowController.showStatusLabel(
                        self.waiting_label)
            elif newstate == STREAM_PROPOSING:
                self.videoWindowController.showStatusLabel(
                    NSLocalizedString("Adding Video...", "Audio status label"))
Exemple #17
0
    def refresh_transfer_rate(self):
        incoming_transfer_rate = 0
        outgoing_transfer_rate = 0
        for item in self.listView.subviews().copy():
            if item.transfer and item.transfer.transfer_rate is not None:
                if isinstance(item.transfer, IncomingFileTransferHandler):
                    incoming_transfer_rate += item.transfer.transfer_rate
                elif isinstance(item.transfer,
                                OutgoingPushFileTransferHandler):
                    outgoing_transfer_rate += item.transfer.transfer_rate
                elif isinstance(item.transfer,
                                OutgoingPullFileTransferHandler):
                    incoming_transfer_rate += item.transfer.transfer_rate

        if incoming_transfer_rate or outgoing_transfer_rate:
            if incoming_transfer_rate and outgoing_transfer_rate:
                f1 = format_size(incoming_transfer_rate, bits=True)
                f2 = format_size(outgoing_transfer_rate, bits=True)
                text = NSLocalizedString(
                    "Incoming %s/s", "Label") % f1 + ", " + NSLocalizedString(
                        "Outgoing %s/s", "Label") % f2
            elif incoming_transfer_rate:
                f = format_size(incoming_transfer_rate, bits=True)
                text = NSLocalizedString("Incoming %s/s", "Label") % f
            elif outgoing_transfer_rate:
                f = format_size(outgoing_transfer_rate, bits=True)
                text = NSLocalizedString("Outgoing %s/s", "Label") % f
            self.transferSpeed.setStringValue_(text)
        else:
            self.transferSpeed.setStringValue_('')
    def updateConfigurationsPopupButton(self):
        self.configurationsButton.removeAllItems()
        if self.conference_configurations:
            self.configurationsButton.addItemWithTitle_(
                NSLocalizedString("Select Configuration", "Menu item"))
            self.configurationsButton.lastItem().setEnabled_(False)
            self.configurationsButton.selectItem_(
                self.configurationsButton.lastItem())
            self.configurationsButton.addItemWithTitle_(
                NSLocalizedString("None", "Menu item"))
            self.configurationsButton.lastItem().setEnabled_(True)
            for key in list(self.conference_configurations.keys()):
                self.configurationsButton.addItemWithTitle_(key)
                object = self.conference_configurations[key]
                item = self.configurationsButton.lastItem()
                item.setRepresentedObject_(object)
                if self.selected_configuration and self.selected_configuration == key:
                    self.configurationsButton.selectItem_(item)
        else:
            self.configurationsButton.addItemWithTitle_(
                NSLocalizedString("No configurations saved", "Menu item"))
            self.configurationsButton.lastItem().setEnabled_(False)

        self.configurationsButton.menu().addItem_(NSMenuItem.separatorItem())
        self.configurationsButton.addItemWithTitle_(self.saveButtonTitle)
        self.configurationsButton.lastItem().setEnabled_(True)
        self.configurationsButton.addItemWithTitle_(self.renameButtonTitle)
        self.configurationsButton.lastItem().setEnabled_(
            True if self.selected_configuration else False)
        self.configurationsButton.addItemWithTitle_(self.deleteButtonTitle)
        self.configurationsButton.lastItem().setEnabled_(
            True if self.selected_configuration else False)
Exemple #19
0
    def render_pidf(self):
        if not self.contact:
            return
        has_locations = False
        status_label = ''
        if self.contact.presence_state['devices']:
            has_locations = any(device['location'] for device in list(self.contact.presence_state['devices'].values()) if device['location'] is not None)
            count = len(self.contact.presence_state['devices'])
            if count == 1:
                status_label = NSLocalizedString("One device available", "Label")
            elif count > 1:
                status_label = NSLocalizedString("%d devices available" % count, "Label")

        splitViewFrame = self.splitView.frame()
        mapViewFrame = self.mapViewSplitView.frame()
        pidfViewFrame = self.pidfView.frame()

        if has_locations:
            if mapViewFrame.size.height == 0:
                mapViewFrame.size.height = SPLITTER_HEIGHT
                self.mapViewSplitView.setFrame_(mapViewFrame)
                pidfViewFrame.size.height -= SPLITTER_HEIGHT
                self.pidfView.setFrame_(pidfViewFrame)
            self.mapView.setContact(self.contact)
            nr_countries = len(self.mapView.selectedCountries)
            if nr_countries == 1:
                status_label += NSLocalizedString(" in one country", "Label")
            elif nr_countries > 1:
                status_label +=  NSLocalizedString(" in %d countries" % nr_countries, "Label")
        else:
            mapViewFrame.size.height = 0
            self.mapViewSplitView.setFrame_(mapViewFrame)
            pidfViewFrame.size.height = splitViewFrame.size.height
            self.pidfView.setFrame_(pidfViewFrame)

        self.statusLabel.setStringValue_(status_label)

        text = ''
        for pidf in self.contact.pidfs:
            text += self.build_pidf_text(pidf) + '\n\n'

        if self.contact.presence_state['pending_authorizations']:
            text += "Pending authorizations:\n"

        pending_authorizations = self.contact.presence_state['pending_authorizations']
        for key in list(pending_authorizations.keys()):
            text += "    Subscription to %s from account %s\n" % (sip_prefix_pattern.sub('', key), pending_authorizations[key])

        self.presenceText.textStorage().deleteCharactersInRange_(NSMakeRange(0, self.presenceText.textStorage().length()))
        astring = NSAttributedString.alloc().initWithString_(text)
        self.presenceText.textStorage().appendAttributedString_(astring)

        image = presence_status_for_contact(self.contact)
        if image:
            icon = NSImage.imageNamed_(image)
            icon.setScalesWhenResized_(True)
            icon.setSize_(NSMakeSize(12,12))
            self.presence_icon.setImage_(icon)
Exemple #20
0
def build_updates_page():
    '''available/pending updates'''
    page_name = u'updates.html'

    # need to consolidate/centralize this flag. Accessing it this way is ugly.
    if NSApp.delegate().mainWindowController._update_in_progress:
        return build_update_status_page()

    item_list = MunkiItems.getEffectiveUpdateList()

    other_updates = [
        item for item in MunkiItems.getOptionalInstallItems()
        if item['status'] == 'update-available'
    ]

    page = {}
    page['update_rows'] = u''
    page['hide_progress_spinner'] = u'hidden'
    page['hide_other_updates'] = u'hidden'
    page['install_all_button_classes'] = u''

    item_template = get_template('update_row_template.html')

    if item_list:
        for item in item_list:
            escapeAndQuoteCommonFields(item)
            page['update_rows'] += item_template.safe_substitute(item)
    elif not other_updates:
        status_results_template = get_template('status_results_template.html')
        alert = {}
        alert['primary_status_text'] = NSLocalizedString(
            u"Your software is up to date.",
            u"No Pending Updates primary text")
        alert['secondary_status_text'] = NSLocalizedString(
            u"There is no new software for your computer at this time.",
            u"No Pending Updates secondary text")
        alert['hide_progress_bar'] = u'hidden'
        alert['progress_bar_value'] = u''
        page['update_rows'] = status_results_template.safe_substitute(alert)

    count = len(item_list)
    page['update_count'] = msclib.updateCountMessage(count)
    page['install_btn_label'] = msclib.getInstallAllButtonTextForCount(count)
    page['warning_text'] = get_warning_text()

    page['other_updates_header_message'] = NSLocalizedString(
        u"Other available updates", u"Other Available Updates label")
    page['other_update_rows'] = u''

    if other_updates:
        page['hide_other_updates'] = u''
        for item in other_updates:
            escapeAndQuoteCommonFields(item)
            page['other_update_rows'] += item_template.safe_substitute(item)

    footer = get_template('footer_template.html', raw=True)
    generate_page(page_name, 'updates_template.html', page, footer=footer)
Exemple #21
0
def build_item_not_found_page(page_name):
    '''Build item not found page'''
    page = {}
    page['item_not_found_title'] = NSLocalizedString(
        u"Not Found", u"Item Not Found title")
    page['item_not_found_message'] = NSLocalizedString(
        u"Cannot display the requested item.", u"Item Not Found message")
    footer = get_template('footer_template.html', raw=True)
    generate_page(page_name, 'page_not_found_template.html', page, footer=footer)
Exemple #22
0
def build_category_items_html():
    '''Returns HTML for the items on the Categories page'''
    all_items = MunkiItems.getOptionalInstallItems()
    if all_items:
        category_list = []
        for item in all_items:
            if 'category' in item and item['category'] not in category_list:
                category_list.append(item['category'])

        item_template = get_template('category_item_template.html')
        item_html = u''
        for category in sorted(category_list):
            category_data = {}
            category_data['category_name_escaped'] = escape_html(category)
            category_data['category_link'] = u'category-%s.html' % quote(category)
            category_items = [item for item in all_items if item.get('category') == category]
            shuffle(category_items)
            category_data['item1_icon'] = category_items[0]['icon']
            category_data['item1_display_name_escaped'] = escape_html(
                 category_items[0]['display_name'])
            category_data['item1_detail_link'] = category_items[0]['detail_link']
            if len(category_items) > 1:
                category_data['item2_display_name_escaped'] = escape_html(
                    category_items[1]['display_name'])
                category_data['item2_detail_link'] = category_items[1]['detail_link']
            else:
                category_data['item2_display_name_escaped'] = u''
                category_data['item2_detail_link'] = u'#'
            if len(category_items) > 2:
                category_data['item3_display_name_escaped'] = escape_html(
                    category_items[2]['display_name'])
                category_data['item3_detail_link'] = category_items[2]['detail_link']
            else:
                category_data['item3_display_name_escaped'] = u''
                category_data['item3_detail_link'] = u'#'

            item_html += item_template.safe_substitute(category_data)

        # pad with extra empty items so we have a multiple of 3
        if len(category_list) % 3:
            for x in range(3 - (len(category_list) % 3)):
                item_html += u'<div class="lockup"></div>\n'

    else:
        # no items
        status_results_template = get_template('status_results_template.html')
        alert = {}
        alert['primary_status_text'] = NSLocalizedString(
            u"There are no available software items.",
            u"No Items primary text")
        alert['secondary_status_text'] = NSLocalizedString(
            u"Try again later.",
            u"No Items secondary text")
        alert['hide_progress_bar'] = u'hidden'
        alert['progress_bar_value'] = u''
        item_html = status_results_template.safe_substitute(alert)
    return item_html
 def download_didFailWithError_(self, download, error):
     download.cancel()
     BlinkLogger().log_info("Download error: %s" %
                            error.localizedDescription())
     e = error.localizedDescription()
     NSRunAlertPanel(
         NSLocalizedString("Error", "Window title"),
         NSLocalizedString("Error downloading file: %s", "Label") % e,
         NSLocalizedString("OK", "Button title"), "", "")
Exemple #24
0
def normalize_sip_uri_for_outgoing_session(target_uri, account):
    def format_uri(uri,
                   default_domain,
                   idd_prefix=None,
                   prefix=None,
                   strip_digits=None):
        if default_domain is not None:
            if "@" not in uri:
                if _pstn_match_regexp.match(uri):
                    username = strip_addressbook_special_characters(uri)
                    if idd_prefix:
                        username = _pstn_plus_regexp.sub(idd_prefix, username)
                    if strip_digits and len(username) > strip_digits:
                        username = username[strip_digits:]
                    if prefix:
                        username = prefix + username
                else:
                    username = uri
                uri = "%s@%s" % (username, default_domain)
            elif "." not in uri.split("@", 1)[1]:
                uri += "." + default_domain
        if not uri.startswith("sip:") and not uri.startswith("sips:"):
            uri = "sip:%s" % uri
        return uri

    try:
        target_uri = str(target_uri)
    except:
        show_error_panel(
            NSLocalizedString(
                "SIP address must not contain unicode characters: %s", "Label")
            % target_uri)
        return None

    if '@' not in target_uri and isinstance(account, BonjourAccount):
        show_error_panel(
            NSLocalizedString(
                "SIP address must contain host in bonjour mode: %s", "Label") %
            target_uri)
        return None

    target_uri = format_uri(
        target_uri,
        account.id.domain if not isinstance(account, BonjourAccount) else None,
        account.pstn.idd_prefix if not isinstance(account, BonjourAccount) else
        None, account.pstn.prefix if not isinstance(account, BonjourAccount)
        else None, account.pstn.strip_digits
        if not isinstance(account, BonjourAccount) else None)

    try:
        target_uri = SIPURI.parse(target_uri)
    except SIPCoreError:
        show_error_panel(
            NSLocalizedString("Invalid SIP address: %s", "Label") % target_uri)
        return None
    return target_uri
Exemple #25
0
 def _NH_MediaStreamDidNotInitialize(self, sender, data):
     if data.reason == 'MSRPRelayAuthError':
         reason = NSLocalizedString("MSRP relay authentication failed",
                                    "Label")
     else:
         reason = NSLocalizedString("MSRP connection failed", "Label")
     self.sessionController.log_info(reason)
     self.changeStatus(STREAM_FAILED, data.reason)
     NotificationCenter().remove_observer(self, sender=self.stream.handler)
     NotificationCenter().remove_observer(self, sender=self.stream)
    def updateContactsColumnHeader(self):
        found_contacts = len(self.contacts)-2
        if found_contacts == 1:
            title = NSLocalizedString("1 contact found", "Label")
        elif found_contacts > 1:
            title = NSLocalizedString("%d contacts found", "Label") % found_contacts
        else:
            title = NSLocalizedString("Contacts", "Label")

        self.contactTable.tableColumnWithIdentifier_('contacts').headerCell().setStringValue_(title)
 def okClicked_(self, sender):
     if not len(self._participants):
         NSRunAlertPanel(
             NSLocalizedString("Add Participants to the Conference",
                               "Window title"),
             NSLocalizedString("Please add at least one participant. ",
                               "Label"),
             NSLocalizedString("OK", "Button title"), None, None)
     else:
         NSApp.stopModalWithCode_(NSOKButton)
 def _NH_BlinkSessionDidFail(self, sender, data):
     if host is None or host.default_ip is None:
         reason = NSLocalizedString("No Internet connection", "Label")
     else:
         reason = "%s (%s)" % (data.failure_reason.title(), data.code)
         if data.code is not None:
             if data.code == 486:
                 reason = NSLocalizedString("Busy Here", "Label")
             elif data.code == 487:
                 reason = NSLocalizedString("Session Cancelled", "Label")
             elif data.code == 603:
                 reason = NSLocalizedString("Call Declined", "Label")
             elif data.code == 408:
                 if data.originator == 'local':
                     reason = NSLocalizedString("Network Timeout", "Label")
                 else:
                     reason = NSLocalizedString("User Unreachable", "Label")
             elif data.code == 480:
                 reason = NSLocalizedString("User Not Online", "Label")
             elif data.code == 482:
                 reason = NSLocalizedString("User Unreachable", "Label")
             elif data.code >= 500 and data.code < 600:
                 reason = NSLocalizedString(
                     "Server Failure (%s)" % data.code, "Label")
         if self.videoWindowController:
             self.videoWindowController.showStatusLabel(reason)
     self.stopTimers()
     self.changeStatus(STREAM_FAILED)
Exemple #29
0
    def _NH_SIPEngineTransportDidDisconnect(self, notification):
        self.transport_lost_timestamp = int(time.time())

        transport = '%s:%s' % (notification.data.transport,
                               notification.data.remote_address)
        try:
            self.active_transports.remove(transport)
        except KeyError:
            return

        for account_info in self.contactsWindowController.accounts:
            account = account_info.account

            if account is BonjourAccount():
                continue

            if not account.enabled:
                continue

            if account_info.registrar != transport:
                continue

            account_info.register_state = 'failed'

            if host is None or host.default_ip is None:
                account_info.register_failure_reason = NSLocalizedString(
                    "No Internet connection", "Label")
            else:
                account_info.register_failure_reason = NSLocalizedString(
                    "Connection failed", "Label")

            self.contactsWindowController.refreshAccountList()
            BlinkLogger().log_info('Reconnecting account %s' % account.id)

            account.reregister()
            account.resubscribe()
            presence_state = account.presence_state
            account.presence_state = None
            account.presence_state = presence_state

        if notification.data.reason != 'Success':
            BlinkLogger().log_info(
                "%s connection %s <-> %s lost" %
                (notification.data.transport, notification.data.local_address,
                 notification.data.remote_address))
            #nc_title = NSLocalizedString("Connection failed", "Label")
            #nc_body = NSLocalizedString("Remote Address", "Label") + " %s:%s" % (notification.data.transport, notification.data.remote_address)
            #self.gui_notify(nc_title, nc_body)

        else:
            NotificationCenter().post_notification(
                "BlinkTransportFailed",
                data=NotificationData(transport=transport))
 def runModalForRename_(self, name):
     self.nameText.setStringValue_(name)
     self.window.setTitle_(NSLocalizedString("Rename Group",
                                             "Window title"))
     self.caption.setStringValue_(
         NSLocalizedString("Enter a new name for the group:", "Label"))
     self.window.makeKeyAndOrderFront_(None)
     rc = NSApp.runModalForWindow_(self.window)
     self.window.orderOut_(self)
     if rc == NSOKButton:
         return str(self.nameText.stringValue())
     return None