content
stringlengths
228
999k
pred_label
stringclasses
1 value
pred_score
float64
0.5
1
core.py 51.8 KB Newer Older 1 # Copyright 2010-2011 Le Coz Florent <[email protected]> 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 # # This file is part of Poezio. # # Poezio 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, version 3 of the License. # # Poezio 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 Poezio. If not, see <http://www.gnu.org/licenses/>. 17 18 from gettext import (bindtextdomain, textdomain, bind_textdomain_codeset, gettext as _) 19 from os.path import isfile 20 21 22 from time import sleep 23 import os 24 import re 25 26 import sys import shlex 27 import curses 28 import threading 29 import traceback 30 31 from datetime import datetime 32 33 import common 34 import theme 35 36 import logging 37 38 from sleekxmpp.xmlstream.stanzabase import JID 39 log = logging.getLogger(__name__) 40 41 import multiuserchat as muc 42 import tabs 43 import windows 44 45 from connection import connection 46 from config import config 47 from logger import logger 48 49 from user import User from room import Room 50 from roster import Roster, RosterGroup, roster 51 from contact import Contact, Resource 52 from text_buffer import TextBuffer 53 from keyboard import read_char 54 55 56 # http://xmpp.org/extensions/xep-0045.html#errorstatus ERROR_AND_STATUS_CODES = { 57 58 59 60 61 62 63 64 '401': _('A password is required'), '403': _('You are banned from the room'), '404': _('The room does\'nt exist'), '405': _('Your are not allowed to create a new room'), '406': _('A reserved nick must be used'), '407': _('You are not in the member list'), '409': _('This nickname is already in use or has been reserved'), '503': _('The maximum number of users has been reached'), 65 66 } 67 68 69 70 71 72 73 SHOW_NAME = { 'dnd': _('busy'), 'away': _('away'), 'xa': _('not available'), 'chat': _('chatty'), '': _('available') } 74 75 76 resize_lock = threading.Lock() 77 class Core(object): 78 """ 79 User interface using ncurses 80 """ 81 def __init__(self, xmpp): 82 83 84 # All uncaught exception are given to this callback, instead # of being displayed on the screen and exiting the program. sys.excepthook = self.on_exception 85 self.running = True 86 87 88 self.stdscr = curses.initscr() self.init_curses(self.stdscr) self.xmpp = xmpp 89 90 91 # a unique buffer used to store global informations # that are displayed in almost all tabs, in an # information window. 92 self.information_buffer = TextBuffer() 93 self.information_win_size = config.get('info_win_height', 2, 'var') 94 default_tab = tabs.InfoTab(self) if self.xmpp.anon\ 95 else tabs.RosterInfoTab(self) 96 default_tab.on_gain_focus() 97 self.tabs = [default_tab] 98 self.resize_timer = None 99 self.previous_tab_nb = 0 100 self.own_nick = config.get('own_nick', '') or self.xmpp.boundjid.user 101 102 103 104 105 106 107 # global commands, available from all tabs # a command is tuple of the form: # (the function executing the command. Takes a string as argument, # a string representing the help message, # a completion function, taking a Input as argument. Can be None) # The completion function should return True if a completion was # made ; False otherwise 108 self.commands = { 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 'help': (self.command_help, '\_o< KOIN KOIN KOIN', None), 'join': (self.command_join, _("Usage: /join [room_name][@server][/nick] [password]\nJoin: Join the specified room. You can specify a nickname after a slash (/). If no nickname is specified, you will use the default_nick in the configuration file. You can omit the room name: you will then join the room you\'re looking at (useful if you were kicked). You can also provide a room_name without specifying a server, the server of the room you're currently in will be used. You can also provide a password to join the room.\nExamples:\n/join [email protected]\n/join [email protected]/John\n/join room2\n/join /me_again\n/join\n/join [email protected]/my_nick password\n/join / password"), self.completion_join), 'exit': (self.command_quit, _("Usage: /exit\nExit: Just disconnect from the server and exit poezio."), None), 'next': (self.rotate_rooms_right, _("Usage: /next\nNext: Go to the next room."), None), 'n': (self.rotate_rooms_right, _("Usage: /n\nN: Go to the next room."), None), 'prev': (self.rotate_rooms_left, _("Usage: /prev\nPrev: Go to the previous room."), None), 'p': (self.rotate_rooms_left, _("Usage: /p\nP: Go to the previous room."), None), 'win': (self.command_win, _("Usage: /win <number>\nWin: Go to the specified room."), None), 'w': (self.command_win, _("Usage: /w <number>\nW: Go to the specified room."), None), 'show': (self.command_show, _("Usage: /show <availability> [status]\nShow: Change your availability and (optionaly) your status. The <availability> argument is one of \"avail, available, ok, here, chat, away, afk, dnd, busy, xa\" and the optional [status] argument will be your status message"), None), 'away': (self.command_away, _("Usage: /away [message]\nAway: Sets your availability to away and (optional) sets your status message. This is equivalent to '/show away [message]'"), None), 'busy': (self.command_busy, _("Usage: /busy [message]\nBusy: Sets your availability to busy and (optional) sets your status message. This is equivalent to '/show busy [message]'"), None), 'avail': (self.command_avail, _("Usage: /avail [message]\nAvail: Sets your availability to available and (optional) sets your status message. This is equivalent to '/show available [message]'"), None), 'available': (self.command_avail, _("Usage: /available [message]\nAvailable: Sets your availability to available and (optional) sets your status message. This is equivalent to '/show available [message]'"), None), 'bookmark': (self.command_bookmark, _("Usage: /bookmark [roomname][/nick]\nBookmark: Bookmark the specified room (you will then auto-join it on each poezio start). This commands uses the same syntaxe as /join. Type /help join for syntaxe examples. Note that when typing \"/bookmark\" on its own, the room will be bookmarked with the nickname you\'re currently using in this room (instead of default_nick)"), None), 'set': (self.command_set, _("Usage: /set <option> [value]\nSet: Sets the value to the option in your configuration file. You can, for example, change your default nickname by doing `/set default_nick toto` or your resource with `/set resource blabla`. You can also set an empty value (nothing) by providing no [value] after <option>."), None), 'whois': (self.command_whois, _('Usage: /whois <nickname>\nWhois: Request many informations about the user.'), None), 'theme': (self.command_theme, _('Usage: /theme\nTheme: Reload the theme defined in the config file.'), None), 127 'list': (self.command_list, _('Usage: /list\n/List: get the list of public chatrooms on the specified server'), self.completion_list), 128 129 } 130 self.key_func = { 131 132 "KEY_PPAGE": self.scroll_page_up, "KEY_NPAGE": self.scroll_page_down, 133 "KEY_F(5)": self.rotate_rooms_left, 134 "^P": self.rotate_rooms_left, 135 'kLFT3': self.rotate_rooms_left, 136 "KEY_F(6)": self.rotate_rooms_right, 137 138 "^N": self.rotate_rooms_right, 'kRIT3': self.rotate_rooms_right, 139 140 "KEY_F(7)": self.shrink_information_win, "KEY_F(8)": self.grow_information_win, 141 "KEY_RESIZE": self.call_for_resize, 142 'M-e': self.go_to_important_room, 143 'M-r': self.go_to_roster, 144 145 'M-z': self.go_to_previous_tab, 'M-v': self.move_separator, 146 '^L': self.full_screen_redraw, 147 148 } 149 150 151 152 # Add handlers self.xmpp.add_event_handler("session_start", self.on_connected) self.xmpp.add_event_handler("groupchat_presence", self.on_groupchat_presence) self.xmpp.add_event_handler("groupchat_message", self.on_groupchat_message) 153 self.xmpp.add_event_handler("groupchat_subject", self.on_groupchat_subject) 154 self.xmpp.add_event_handler("message", self.on_message) 155 156 self.xmpp.add_event_handler("got_online" , self.on_got_online) self.xmpp.add_event_handler("got_offline" , self.on_got_offline) 157 self.xmpp.add_event_handler("roster_update", self.on_roster_update) 158 self.xmpp.add_event_handler("changed_status", self.on_presence) 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 def on_exception(self, typ, value, trace): """ When an exception in raised, open a special tab displaying the traceback and some instructions to make a bug report. """ try: tb_tab = tabs.SimpleTextTab(self, "/!\ Oups, an error occured (this may not be fatal). /!\\\n\nPlease report this bug (by copying the present error message and explaining what you were doing) on the page http://codingteam.net/project/poezio/bugs/add\n\n%s\n\nIf Poezio does not respond anymore, kill it with Ctrl+\\, and sorry about that :(" % ''.join(traceback.format_exception(typ, value, trace))) self.add_tab(tb_tab, focus=True) except Exception: # If an exception is raised in this code, this is # this is fatal, so we exit cleanly and display the traceback curses.endwin() raise 174 175 176 177 178 179 180 def grow_information_win(self): """ """ if self.information_win_size == 14: return self.information_win_size += 1 for tab in self.tabs: 181 tab.on_info_win_size_changed() 182 183 184 185 186 187 188 189 190 self.refresh_window() def shrink_information_win(self): """ """ if self.information_win_size == 0: return self.information_win_size -= 1 for tab in self.tabs: 191 tab.on_info_win_size_changed() 192 self.refresh_window() 193 194 195 def on_got_offline(self, presence): jid = presence['from'] 196 contact = roster.get_contact_by_jid(jid.bare) 197 198 if not contact: return 199 200 201 resource = contact.get_resource_by_fulljid(jid.full) assert resource self.information('%s is offline' % (resource.get_jid()), "Roster") 202 203 204 205 206 # Search all opened tab with this fulljid or the bare jid and add # an information message in all of them tab = self.get_tab_by_name(jid.full) if tab and isinstance(tab, tabs.ConversationTab): self.add_message_to_text_buffer(tab.get_room(), '%s is offline' % (resource.get_jid())) 207 contact.remove_resource(resource) 208 if isinstance(self.current_tab(), tabs.RosterInfoTab): 209 self.refresh_window() 210 211 212 def on_got_online(self, presence): jid = presence['from'] 213 contact = roster.get_contact_by_jid(jid.bare) 214 if not contact: 215 # Todo, handle presence comming from contacts not in roster 216 return 217 218 219 resource = contact.get_resource_by_fulljid(jid.full) assert not resource resource = Resource(jid.full) 220 status = presence['type'] 221 status_message = presence['status'] 222 priority = presence.getPriority() or 0 223 resource.set_status(status_message) 224 225 226 227 resource.set_presence(status) resource.set_priority(priority) contact.add_resource(resource) self.information("%s is online (%s)" % (resource.get_jid().full, status), "Roster") 228 229 230 231 232 233 def on_connected(self, event): """ Called when we are connected and authenticated """ self.information(_("Welcome on Poezio \o/!")) 234 self.information(_("Your JID is %s") % self.xmpp.boundjid.full) 235 236 237 238 239 if not self.xmpp.anon: # request the roster self.xmpp.getRoster() # send initial presence 240 self.xmpp.makePresence().send() 241 242 243 244 245 rooms = config.get('rooms', '') if rooms == '' or not isinstance(rooms, str): return rooms = rooms.split(':') for room in rooms: 246 247 jid = JID(room) if jid.bare == '': 248 return 249 250 if jid.resource != '': nick = jid.resource 251 252 253 254 255 else: default = os.environ.get('USER') if os.environ.get('USER') else 'poezio' nick = config.get('default_nick', '') if nick == '': nick = default 256 257 self.open_new_room(jid.bare, nick, False) muc.join_groupchat(self.xmpp, jid.bare, nick) 258 # if not self.xmpp.anon: 259 260 261 262 263 264 265 266 267 268 269 270 271 # Todo: SEND VCARD return if config.get('jid', '') == '': # Don't send the vcard if we're not anonymous self.vcard_sender.start() # because the user ALREADY has one on the server def on_groupchat_presence(self, presence): """ Triggered whenever a presence stanza is received from a user in a multi-user chat room. Display the presence on the room window and update the presence information of the concerned user """ from_nick = presence['from'].resource from_room = presence['from'].bare 272 room = self.get_room_by_name(from_room) 273 274 275 276 277 code = presence.find('{jabber:client}status') status_codes = set([s.attrib['code'] for s in presence.findall('{http://jabber.org/protocol/muc#user}x/{http://jabber.org/protocol/muc#user}status')]) # Check if it's not an error presence. if presence['type'] == 'error': return self.room_error(presence, from_room) 278 if not room: 279 return 280 281 282 283 284 285 286 287 288 289 290 291 msg = None affiliation = presence['muc']['affiliation'] show = presence['show'] status = presence['status'] role = presence['muc']['role'] jid = presence['muc']['jid'] typ = presence['type'] if not room.joined: # user in the room BEFORE us. # ignore redondant presence message, see bug #1509 if from_nick not in [user.nick for user in room.users]: new_user = User(from_nick, affiliation, show, status, role) room.users.append(new_user) 292 if from_nick == room.own_nick: 293 294 room.joined = True new_user.color = theme.COLOR_OWN_NICK 295 self.add_message_to_text_buffer(room, _("Your nickname is %s") % (from_nick)) 296 if '170' in status_codes: 297 self.add_message_to_text_buffer(room, 'Warning: this room is publicly logged') 298 else: 299 300 301 302 303 304 305 306 change_nick = '303' in status_codes kick = '307' in status_codes and typ == 'unavailable' user = room.get_user_by_name(from_nick) # New user if not user: self.on_user_join(room, from_nick, affiliation, show, status, role, jid) # nick change elif change_nick: 307 self.on_user_nick_change(room, presence, user, from_nick, from_room) 308 309 # kick elif kick: 310 self.on_user_kicked(room, presence, user, from_nick) 311 312 # user quit elif typ == 'unavailable': 313 self.on_user_leave_groupchat(room, user, jid, status, from_nick, from_room) 314 315 # status change else: 316 self.on_user_change_status(room, user, from_nick, from_room, affiliation, role, show, status) 317 self.refresh_window() 318 self.doupdate() 319 320 321 322 323 324 325 326 327 328 def on_user_join(self, room, from_nick, affiliation, show, status, role, jid): """ When a new user joins a groupchat """ room.users.append(User(from_nick, affiliation, show, status, role)) hide_exit_join = config.get('hide_exit_join', -1) if hide_exit_join != 0: if not jid.full: 329 self.add_message_to_text_buffer(room, _('%(spec)s "[%(nick)s]" joined the room') % {'nick':from_nick.replace('"', '\\"'), 'spec':theme.CHAR_JOIN.replace('"', '\\"')}, colorized=True) 330 else: 331 self.add_message_to_text_buffer(room, _('%(spec)s "[%(nick)s]" "(%(jid)s)" joined the room') % {'spec':theme.CHAR_JOIN.replace('"', '\\"'), 'nick':from_nick.replace('"', '\\"'), 'jid':jid.full}, colorized=True) 332 333 334 335 336 337 def on_user_nick_change(self, room, presence, user, from_nick, from_room): new_nick = presence.find('{http://jabber.org/protocol/muc#user}x/{http://jabber.org/protocol/muc#user}item').attrib['nick'] if user.nick == room.own_nick: room.own_nick = new_nick # also change our nick in all private discussion of this room 338 for _tab in self.tabs: 339 if isinstance(_tab, tabs.PrivateTab) and JID(_tab.get_name()).bare == room.name: 340 _tab.get_room().own_nick = new_nick 341 user.change_nick(new_nick) 342 self.add_message_to_text_buffer(room, _('"[%(old)s]" is now known as "[%(new)s]"') % {'old':from_nick.replace('"', '\\"'), 'new':new_nick.replace('"', '\\"')}, colorized=True) 343 344 345 # rename the private tabs if needed private_room = self.get_room_by_name('%s/%s' % (from_room, from_nick)) if private_room: 346 self.add_message_to_text_buffer(private_room, _('"[%(old_nick)s]" is now known as "[%(new_nick)s]"') % {'old_nick':from_nick.replace('"', '\\"'), 'new_nick':new_nick.replace('"', '\\"')}, colorized=True) 347 new_jid = JID(private_room.name).bare+'/'+new_nick 348 private_room.name = new_jid 349 350 351 352 353 354 355 356 def on_user_kicked(self, room, presence, user, from_nick): """ When someone is kicked """ room.users.remove(user) by = presence.find('{http://jabber.org/protocol/muc#user}x/{http://jabber.org/protocol/muc#user}item/{http://jabber.org/protocol/muc#user}actor') reason = presence.find('{http://jabber.org/protocol/muc#user}x/{http://jabber.org/protocol/muc#user}item/{http://jabber.org/protocol/muc#user}reason') 357 by = by.attrib['jid'] if by is not None else None 358 reason = reason.text if reason else '' 359 360 361 if from_nick == room.own_nick: # we are kicked room.disconnect() if by: 362 kick_msg = _('%(spec)s [You] have been kicked by "[%(by)s]"') % {'spec': theme.CHAR_KICK.replace('"', '\\"'), 'by':by} 363 else: 364 kick_msg = _('%(spec)s [You] have been kicked.') % {'spec':theme.CHAR_KICK.replace('"', '\\"')} 365 366 367 368 369 # try to auto-rejoin if config.get('autorejoin', 'false') == 'true': muc.join_groupchat(self.xmpp, room.name, room.own_nick) else: if by: 370 kick_msg = _('%(spec)s "[%(nick)s]" has been kicked by "[%(by)s]"') % {'spec':theme.CHAR_KICK.replace('"', '\\"'), 'nick':from_nick.replace('"', '\\"'), 'by':by.replace('"', '\\"')} 371 else: 372 kick_msg = _('%(spec)s "[%(nick)s]" has been kicked') % {'spec':theme.CHAR_KICK, 'nick':from_nick.replace('"', '\\"')} 373 374 if reason: kick_msg += _(' Reason: %(reason)s') % {'reason': reason} 375 self.add_message_to_text_buffer(room, kick_msg, colorized=True) 376 377 378 379 380 381 def on_user_leave_groupchat(self, room, user, jid, status, from_nick, from_room): """ When an user leaves a groupchat """ room.users.remove(user) 382 383 384 if room.own_nick == user.nick: # We are now out of the room. Happens with some buggy (? not sure) servers room.disconnect() 385 386 387 hide_exit_join = config.get('hide_exit_join', -1) if config.get('hide_exit_join', -1) >= -1 else -1 if hide_exit_join == -1 or user.has_talked_since(hide_exit_join): if not jid.full: 388 leave_msg = _('%(spec)s "[%(nick)s]" has left the room') % {'nick':from_nick.replace('"', '\\"'), 'spec':theme.CHAR_QUIT.replace('"', '\\"')} 389 else: 390 leave_msg = _('%(spec)s "[%(nick)s]" "(%(jid)s)" has left the room') % {'spec':theme.CHAR_QUIT.replace('"', '\\"'), 'nick':from_nick.replace('"', '\\"'), 'jid':jid.full.replace('"', '\\"')} 391 392 if status: leave_msg += ' (%s)' % status 393 self.add_message_to_text_buffer(room, leave_msg, colorized=True) 394 395 396 private_room = self.get_room_by_name('%s/%s' % (from_room, from_nick)) if private_room: if not status: 397 self.add_message_to_text_buffer(private_room, _('%(spec)s "[%(nick)s]" has left the room') % {'nick':from_nick.replace('"', '\\"'), 'spec':theme.CHAR_QUIT.replace('"', '\\"')}, colorized=True) 398 else: 399 self.add_message_to_text_buffer(private_room, _('%(spec)s "[%(nick)s]" has left the room "(%(status)s)"') % {'nick':from_nick.replace('"', '\\"'), 'spec':theme.CHAR_QUIT, 'status': status.replace('"', '\\"')}, colorized=True) 400 401 402 403 404 405 def on_user_change_status(self, room, user, from_nick, from_room, affiliation, role, show, status): """ When an user changes her status """ # build the message 406 407 display_message = False # flag to know if something significant enough # to be displayed has changed 408 msg = _('"%s" changed: ')% from_nick.replace('"', '\\"') 409 if affiliation != user.affiliation: 410 msg += _('affiliation: %s, ') % affiliation 411 display_message = True 412 if role != user.role: 413 msg += _('role: %s, ') % role 414 display_message = True 415 if show != user.show and show in list(SHOW_NAME.keys()): 416 msg += _('show: %s, ') % SHOW_NAME[show] 417 418 display_message = True if status and status != user.status: 419 msg += _('status: %s, ') % status 420 421 422 display_message = True if not display_message: return 423 msg = msg[:-2] # remove the last ", " 424 425 426 427 428 429 430 431 432 433 hide_status_change = config.get('hide_status_change', -1) if config.get('hide_status_change', -1) >= -1 else -1 if (hide_status_change == -1 or \ user.has_talked_since(hide_status_change) or\ user.nick == room.own_nick)\ and\ (affiliation != user.affiliation or\ role != user.role or\ show != user.show or\ status != user.status): # display the message in the room 434 self.add_message_to_text_buffer(room, msg, colorized=True) 435 436 private_room = self.get_room_by_name('%s/%s' % (from_room, from_nick)) if private_room: # display the message in private 437 self.add_message_to_text_buffer(private_room, msg, colorized=True) 438 439 440 # finally, effectively change the user status user.update(affiliation, show, status, role) 441 442 443 444 445 446 def on_message(self, message): """ When receiving private message from a muc OR a normal message (from one of our contacts) """ if message['type'] == 'groupchat': 447 return 448 449 # Differentiate both type of messages, and call the appropriate handler. jid_from = message['from'] 450 for tab in self.tabs: 451 if tab.get_name() == jid_from.bare and isinstance(tab, tabs.MucTab): 452 if message['type'] == 'error': 453 return self.room_error(message, tab.get_room().name) 454 455 else: return self.on_groupchat_private_message(message) 456 457 458 459 460 461 462 return self.on_normal_message(message) def on_groupchat_private_message(self, message): """ We received a Private Message (from someone in a Muc) """ jid = message['from'] 463 nick_from = jid.resource 464 room_from = jid.bare 465 466 room = self.get_room_by_name(jid.full) # get the tab with the private conversation if not room: # It's the first message we receive: create the tab 467 room = self.open_private_window(room_from, nick_from, False) 468 469 470 if not room: return body = message['body'] 471 472 473 room.add_message(body, time=None, nickname=nick_from, colorized=False, forced_user=self.get_room_by_name(room_from).get_user_by_name(nick_from)) 474 self.refresh_window() 475 self.doupdate() 476 477 478 479 480 481 def focus_tab_named(self, tab_name): for tab in self.tabs: if tab.get_name() == tab_name: self.command_win('%s' % (tab.nb,)) 482 483 484 485 def on_normal_message(self, message): """ When receiving "normal" messages (from someone in our roster) """ 486 jid = message['from'] 487 488 489 body = message['body'] if not body: return 490 491 492 493 494 495 496 497 # We first check if we have a conversation opened with this precise resource conversation = self.get_tab_by_name(jid.full) if not conversation: # If not, we search for a conversation with the bare jid conversation = self.get_tab_by_name(jid.bare) if not conversation: # We create the conversation with the bare Jid if nothing was found conversation = self.open_conversation_window(jid.bare, False) 498 499 500 501 502 if roster.get_contact_by_jid(jid.bare): remote_nick = roster.get_contact_by_jid(jid.bare).get_name() else: remote_nick = jid.full conversation.get_room().add_message(body, None, remote_nick, False, theme.COLOR_REMOTE_USER) 503 504 if self.current_tab() is not conversation: conversation.set_color_state(theme.COLOR_TAB_PRIVATE) 505 self.refresh_window() 506 507 508 509 def on_presence(self, presence): """ """ 510 jid = presence['from'] 511 contact = roster.get_contact_by_jid(jid.bare) 512 513 514 515 516 517 if not contact: return resource = contact.get_resource_by_fulljid(jid.full) if not resource: return status = presence['type'] 518 status_message = presence['status'] 519 520 521 priority = presence.getPriority() or 0 resource.set_presence(status) resource.set_priority(priority) 522 resource.set_status(status_message) 523 if isinstance(self.current_tab(), tabs.RosterInfoTab): 524 self.refresh_window() 525 526 527 528 529 530 def on_roster_update(self, iq): """ A subscription changed, or we received a roster item after a roster request, etc """ 531 532 for item in iq.findall('{jabber:iq:roster}query/{jabber:iq:roster}item'): jid = item.attrib['jid'] 533 contact = roster.get_contact_by_jid(jid) 534 535 if not contact: contact = Contact(jid) 536 roster.add_contact(contact, jid) 537 538 539 540 if 'ask' in item.attrib: contact.set_ask(item.attrib['ask']) else: contact.set_ask(None) 541 542 543 544 if 'name' in item.attrib: contact.set_name(item.attrib['name']) else: contact.set_name(None) 545 546 547 if item.attrib['subscription']: contact.set_subscription(item.attrib['subscription']) groups = item.findall('{jabber:iq:roster}group') 548 roster.edit_groups_of_contact(contact, [group.text for group in groups]) 549 if isinstance(self.current_tab(), tabs.RosterInfoTab): 550 self.refresh_window() 551 552 553 554 555 556 557 558 def full_screen_redraw(self): """ Completely erase and redraw the screen """ self.stdscr.clear() self.call_for_resize() 559 560 561 562 563 564 565 def call_for_resize(self): """ Starts a very short timer. If no other terminal resize occured in this delay then poezio is REALLY resize. This is to avoid multiple unnecessary software resizes (this can be heavy on resource on slow computers or networks) """ 566 567 568 569 570 571 572 573 574 with resize_lock: if self.resize_timer: # a recent terminal resize occured. # Cancel the programmed software resize self.resize_timer.cancel() # add the new timer self.resize_timer = threading.Timer(0.1, self.resize_window) self.resize_timer.start() # self.resize_window() 575 576 577 578 579 def resize_window(self): """ Resize the whole screen """ 580 581 with resize_lock: for tab in self.tabs: 582 tab.resize() 583 self.refresh_window() 584 585 def main_loop(self): 586 587 588 """ main loop waiting for the user to press a key """ 589 self.refresh_window() 590 while self.running: 591 self.doupdate() 592 char=read_char(self.stdscr) 593 # search for keyboard shortcut 594 if char in list(self.key_func.keys()): 595 self.key_func[char]() 596 else: 597 self.do_command(char) 598 599 def current_tab(self): 600 601 602 """ returns the current room, the one we are viewing """ 603 return self.tabs[0] 604 605 606 607 608 609 def get_conversation_by_jid(self, jid): """ Return the room of the ConversationTab with the given jid """ for tab in self.tabs: 610 if isinstance(tab, tabs.ConversationTab): 611 612 613 614 if tab.get_name() == jid: return tab.get_room() return None 615 616 617 618 619 620 621 622 623 def get_tab_by_name(self, name): """ Get the tab with the given name. """ for tab in self.tabs: if tab.get_name() == name: return tab return None 624 def get_room_by_name(self, name): 625 626 627 """ returns the room that has this name """ 628 for tab in self.tabs: 629 if (isinstance(tab, tabs.MucTab) or 630 isinstance(tab, tabs.PrivateTab)) and tab.get_name() == name: 631 return tab.get_room() 632 return None 633 634 def init_curses(self, stdscr): 635 636 637 """ ncurses initialization """ 638 curses.curs_set(1) 639 curses.noecho() 640 641 # curses.raw() theme.init_colors() 642 stdscr.keypad(True) 643 644 def reset_curses(self): 645 646 647 648 649 """ Reset terminal capabilities to what they were before ncurses init """ curses.echo() 650 curses.nocbreak() 651 curses.endwin() 652 653 654 655 656 def refresh_window(self): """ Refresh everything """ 657 self.current_tab().set_color_state(theme.COLOR_TAB_CURRENT) 658 self.current_tab().refresh(self.tabs, self.information_buffer, roster) 659 self.doupdate() 660 661 def add_tab(self, new_tab, focus=False): 662 """ 663 664 Appends the new_tab in the tab list and focus it if focus==True 665 """ 666 667 if self.current_tab().nb == 0: self.tabs.append(new_tab) 668 else: 669 670 671 for ta in self.tabs: if ta.nb == 0: self.tabs.insert(self.tabs.index(ta), new_tab) 672 break 673 if focus: 674 self.command_win("%s" % new_tab.nb) 675 676 677 678 679 680 681 682 def open_new_room(self, room, nick, focus=True): """ Open a new tab.MucTab containing a muc Room, using the specified nick """ r = Room(room, nick) new_tab = tabs.MucTab(self, r) self.add_tab(new_tab, focus) 683 self.refresh_window() 684 685 686 687 688 689 690 def go_to_roster(self): self.command_win('0') def go_to_previous_tab(self): self.command_win('%s' % (self.previous_tab_nb,)) 691 692 693 694 695 696 697 def go_to_important_room(self): """ Go to the next room with activity, in this order: - A personal conversation with a new message - A Muc with an highlight - A Muc with any new message """ 698 699 700 for tab in self.tabs: if tab.get_color_state() == theme.COLOR_TAB_PRIVATE: self.command_win('%s' % tab.nb) 701 return 702 703 704 for tab in self.tabs: if tab.get_color_state() == theme.COLOR_TAB_HIGHLIGHT: self.command_win('%s' % tab.nb) 705 return 706 707 708 for tab in self.tabs: if tab.get_color_state() == theme.COLOR_TAB_NEW_MESSAGE: self.command_win('%s' % tab.nb) 709 return 710 711 712 713 for tab in self.tabs: if isinstance(tab, tabs.ChatTab) and not tab.input.is_empty(): self.command_win('%s' % tab.nb) return 714 715 def rotate_rooms_right(self, args=None): 716 717 718 """ rotate the rooms list to the right """ 719 720 721 self.current_tab().on_lose_focus() self.tabs.append(self.tabs.pop(0)) self.current_tab().on_gain_focus() 722 self.refresh_window() 723 724 def rotate_rooms_left(self, args=None): 725 726 727 """ rotate the rooms list to the right """ 728 729 730 self.current_tab().on_lose_focus() self.tabs.insert(0, self.tabs.pop()) self.current_tab().on_gain_focus() 731 self.refresh_window() 732 733 def scroll_page_down(self, args=None): 734 self.current_tab().on_scroll_down() 735 self.refresh_window() 736 737 def scroll_page_up(self, args=None): 738 self.current_tab().on_scroll_up() 739 self.refresh_window() 740 741 def room_error(self, error, room_name): 742 743 744 """ Display the error on the room window """ 745 746 747 748 749 750 room = self.get_room_by_name(room_name) msg = error['error']['type'] condition = error['error']['condition'] code = error['error']['code'] body = error['error']['text'] if not body: 751 if code in list(ERROR_AND_STATUS_CODES.keys()): 752 753 body = ERROR_AND_STATUS_CODES[code] else: 754 755 body = condition or _('Unknown error') if code: 756 757 msg = _('Error: %(code)s - %(msg)s: %(body)s') % {'msg':msg, 'body':body, 'code':code} self.add_message_to_text_buffer(room, msg) 758 else: 759 760 msg = _('Error: %(msg)s: %(body)s') % {'msg':msg, 'body':body} self.add_message_to_text_buffer(room, msg) 761 if code == '401': 762 763 msg = _('To provide a password in order to join the room, type "/join / password" (replace "password" by the real password)') self.add_message_to_text_buffer(room, msg) 764 if code == '409': 765 766 767 if config.get('alternative_nickname', '') != '': self.command_join('%s/%s'% (room.name, room.own_nick+config.get('alternative_nickname', ''))) else: 768 self.add_message_to_text_buffer(room, _('You can join the room with an other nick, by typing "/join /other_nick"')) 769 self.refresh_window() 770 771 def open_conversation_window(self, jid, focus=True): 772 773 774 """ open a new conversation tab and focus it if needed """ 775 new_tab = tabs.ConversationTab(self, jid) 776 # insert it in the rooms 777 self.add_tab(new_tab, focus) 778 self.refresh_window() 779 return new_tab 780 781 def open_private_window(self, room_name, user_nick, focus=True): 782 complete_jid = room_name+'/'+user_nick 783 for tab in self.tabs: # if the room exists, focus it and return 784 if isinstance(tab, tabs.PrivateTab): 785 786 if tab.get_name() == complete_jid: self.command_win('%s' % tab.nb) 787 return tab.get_room() 788 # create the new tab 789 room = self.get_room_by_name(room_name) 790 791 792 if not room: return None own_nick = room.own_nick 793 r = Room(complete_jid, own_nick) # PrivateRoom here 794 new_tab = tabs.PrivateTab(self, r) 795 # insert it in the tabs 796 self.add_tab(new_tab, focus) 797 # self.window.new_room(r) 798 self.refresh_window()
__label__pos
0.652849
1.   2. 主页 3.  /  4. Go 每日一库 5.  /  6. Go 每日一库之 viper 使用详解 Go 每日一库之 viper 使用详解 简介 viper 是一个配置解决方案,拥有丰富的特性: • 支持 JSON/TOML/YAML/HCL/envfile/Java properties 等多种格式的配置文件; • 可以设置监听配置文件的修改,修改时自动加载新的配置; • 从环境变量、命令行选项和io.Reader中读取配置; • 从远程配置系统中读取和监听修改,如 etcd/Consul; • 代码逻辑中显示设置键值。 快速使用 安装: $ go get github.com/spf13/viper 使用: package main import ( "fmt" "log" "github.com/spf13/viper" ) func main() { viper.SetConfigName("config") viper.SetConfigType("toml") viper.AddConfigPath(".") viper.SetDefault("redis.port", 6381) err := viper.ReadInConfig() if err != nil { log.Fatal("read config failed: %v", err) } fmt.Println(viper.Get("app_name")) fmt.Println(viper.Get("log_level")) fmt.Println("mysql ip: ", viper.Get("mysql.ip")) fmt.Println("mysql port: ", viper.Get("mysql.port")) fmt.Println("mysql user: ", viper.Get("mysql.user")) fmt.Println("mysql password: ", viper.Get("mysql.password")) fmt.Println("mysql database: ", viper.Get("mysql.database")) fmt.Println("redis ip: ", viper.Get("redis.ip")) fmt.Println("redis port: ", viper.Get("redis.port")) } 我们使用之前Go 每日一库之 go-ini一文中使用的配置,不过改为 toml 格式。toml 的语法很简单,快速入门请看learn X in Y minutes app_name = "awesome web" # possible values: DEBUG, INFO, WARNING, ERROR, FATAL log_level = "DEBUG" [mysql] ip = "127.0.0.1" port = 3306 user = "dj" password = 123456 database = "awesome" [redis] ip = "127.0.0.1" port = 7381 viper 的使用非常简单,它需要很少的设置。设置文件名(SetConfigName)、配置类型(SetConfigType)和搜索路径(AddConfigPath),然后调用ReadInConfig viper会自动根据类型来读取配置。使用时调用viper.Get方法获取键值。 编译、运行程序: awesome web DEBUG mysql ip: 127.0.0.1 mysql port: 3306 mysql user: dj mysql password: 123456 mysql database: awesome redis ip: 127.0.0.1 redis port: 7381 有几点需要注意: • 设置文件名时不要带后缀; • 搜索路径可以设置多个,viper 会根据设置顺序依次查找; • viper 获取值时使用section.key的形式,即传入嵌套的键名; • 默认值可以调用viper.SetDefault设置。 读取键 viper 提供了多种形式的读取方法。在上面的例子中,我们看到了Get方法的用法。 Get方法返回一个interface{}的值,使用有所不便。 GetType系列方法可以返回指定类型的值。其中,Type 可以为Bool/Float64/Int/String/Time/Duration/IntSlice/StringSlice 但是请注意,如果指定的键不存在或类型不正确,GetType方法返回对应类型的零值 如果要判断某个键是否存在,使用IsSet方法。 另外,GetStringMapGetStringMapString直接以 map 返回某个键下面所有的键值对,前者返回map[string]interface{},后者返回map[string]string AllSettingsmap[string]interface{}返回所有设置。 // 省略包名和 import 部分 func main() { viper.SetConfigName("config") viper.SetConfigType("toml") viper.AddConfigPath(".") err := viper.ReadInConfig() if err != nil { log.Fatal("read config failed: %v", err) } fmt.Println("protocols: ", viper.GetStringSlice("server.protocols")) fmt.Println("ports: ", viper.GetIntSlice("server.ports")) fmt.Println("timeout: ", viper.GetDuration("server.timeout")) fmt.Println("mysql ip: ", viper.GetString("mysql.ip")) fmt.Println("mysql port: ", viper.GetInt("mysql.port")) if viper.IsSet("redis.port") { fmt.Println("redis.port is set") } else { fmt.Println("redis.port is not set") } fmt.Println("mysql settings: ", viper.GetStringMap("mysql")) fmt.Println("redis settings: ", viper.GetStringMap("redis")) fmt.Println("all settings: ", viper.AllSettings()) } 我们在配置文件 config.toml 中添加protocolsports配置: [server] protocols = ["http", "https", "port"] ports = [10000, 10001, 10002] timeout = 3s 编译、运行程序,输出: protocols: [http https port] ports: [10000 10001 10002] timeout: 3s mysql ip: 127.0.0.1 mysql port: 3306 redis.port is set mysql settings: map[database:awesome ip:127.0.0.1 password:123456 port:3306 user:dj] redis settings: map[ip:127.0.0.1 port:7381] all settings: map[app_name:awesome web log_level:DEBUG mysql:map[database:awesome ip:127.0.0.1 password:123456 port:3306 user:dj] redis:map[ip:127.0.0.1 port:7381] server:map[ports:[10000 10001 10002] protocols:[http https port]]] 如果将配置中的redis.port注释掉,将输出redis.port is not set 上面的示例中还演示了如何使用time.Duration类型,只要是time.ParseDuration接受的格式都可以,例如3s2min1min30s等。 设置键值 viper 支持在多个地方设置,使用下面的顺序依次读取: • 调用Set显示设置的; • 命令行选项; • 环境变量; • 配置文件; • 默认值。 viper.Set 如果某个键通过viper.Set设置了值,那么这个值的优先级最高。 viper.Set("redis.port", 5381) 如果将上面这行代码放到程序中,运行程序,输出的redis.port将是 5381。 命令行选项 如果一个键没有通过viper.Set显示设置值,那么获取时将尝试从命令行选项中读取。如果有,优先使用。viper 使用 pflag 库来解析选项。我们首先在init方法中定义选项,并且调用viper.BindPFlags绑定选项到配置中: func init() { pflag.Int("redis.port", 8381, "Redis port to connect") // 绑定命令行 viper.BindPFlags(pflag.CommandLine) } 然后,在main方法开头处调用pflag.Parse解析选项。 编译、运行程序: $ ./main.exe --redis.port 9381 awesome web DEBUG mysql ip: 127.0.0.1 mysql port: 3306 mysql user: dj mysql password: 123456 mysql database: awesome redis ip: 127.0.0.1 redis port: 9381 如何不传入选项: $ ./main.exe awesome web DEBUG mysql ip: 127.0.0.1 mysql port: 3306 mysql user: dj mysql password: 123456 mysql database: awesome redis ip: 127.0.0.1 redis port: 7381 注意,这里并不会使用选项redis.port的默认值。 但是,如果通过下面的方法都无法获得键值,那么返回选项默认值(如果有)。试试注释掉配置文件中redis.port看看效果。 环境变量 如果前面都没有获取到键值,将尝试从环境变量中读取。我们既可以一个个绑定,也可以自动全部绑定。 init方法中调用AutomaticEnv方法绑定全部环境变量: func init() { // 绑定环境变量 viper.AutomaticEnv() } 为了验证是否绑定成功,我们在main方法中将环境变量 GOPATH 打印出来: func main() { // 省略部分代码 fmt.Println("GOPATH: ", viper.Get("GOPATH")) } 通过 系统 -> 高级设置 -> 新建 创建一个名为redis.port的环境变量,值为 10381。运行程序,输出的redis.port值为 10381,并且输出中有 GOPATH 信息。 也可以单独绑定环境变量: func init() { // 绑定环境变量 viper.BindEnv("redis.port") viper.BindEnv("go.path", "GOPATH") } func main() { // 省略部分代码 fmt.Println("go path: ", viper.Get("go.path")) } 调用BindEnv方法,如果只传入一个参数,则这个参数既表示键名,又表示环境变量名。如果传入两个参数,则第一个参数表示键名,第二个参数表示环境变量名。 还可以通过viper.SetEnvPrefix方法设置环境变量前缀,这样一来,通过AutomaticEnv和一个参数的BindEnv绑定的环境变量,在使用Get的时候,viper 会自动加上这个前缀再从环境变量中查找。 如果对应的环境变量不存在,viper 会自动将键名全部转为大写再查找一次。所以,使用键名gopath也能读取环境变量GOPATH的值。 配置文件 如果经过前面的途径都没能找到该键,viper 接下来会尝试从配置文件中查找。为了避免环境变量的影响,需要删除redis.port这个环境变量。 快速使用中的示例。 默认值 在上面的快速使用一节,我们已经看到了如何设置默认值,这里就不赘述了。 读取配置 io.Reader中读取 viper 支持从io.Reader中读取配置。这种形式很灵活,来源可以是文件,也可以是程序中生成的字符串,甚至可以从网络连接中读取的字节流。 package main import ( "bytes" "fmt" "log" "github.com/spf13/viper" ) func main() { viper.SetConfigType("toml") tomlConfig := []byte(` app_name = "awesome web" # possible values: DEBUG, INFO, WARNING, ERROR, FATAL log_level = "DEBUG" [mysql] ip = "127.0.0.1" port = 3306 user = "dj" password = 123456 database = "awesome" [redis] ip = "127.0.0.1" port = 7381 `) err := viper.ReadConfig(bytes.NewBuffer(tomlConfig)) if err != nil { log.Fatal("read config failed: %v", err) } fmt.Println("redis port: ", viper.GetInt("redis.port")) } Unmarshal viper 支持将配置Unmarshal到一个结构体中,为结构体中的对应字段赋值。 package main import ( "fmt" "log" "github.com/spf13/viper" ) type Config struct { AppName string LogLevel string MySQL MySQLConfig Redis RedisConfig } type MySQLConfig struct { IP string Port int User string Password string Database string } type RedisConfig struct { IP string Port int } func main() { viper.SetConfigName("config") viper.SetConfigType("toml") viper.AddConfigPath(".") err := viper.ReadInConfig() if err != nil { log.Fatal("read config failed: %v", err) } var c Config viper.Unmarshal(&c) fmt.Println(c.MySQL) } 编译,运行程序,输出: {127.0.0.1 3306 dj 123456 awesome} 保存配置 有时候,我们想要将程序中生成的配置,或者所做的修改保存下来。viper 提供了接口! • WriteConfig:将当前的 viper 配置写到预定义路径,如果没有预定义路径,返回错误。将会覆盖当前配置; • SafeWriteConfig:与上面功能一样,但是如果配置文件存在,则不覆盖; • WriteConfigAs:保存配置到指定路径,如果文件存在,则覆盖; • SafeWriteConfig:与上面功能一样,但是入股配置文件存在,则不覆盖。 下面我们通过程序生成一个config.toml配置: package main import ( "log" "github.com/spf13/viper" ) func main() { viper.SetConfigName("config") viper.SetConfigType("toml") viper.AddConfigPath(".") viper.Set("app_name", "awesome web") viper.Set("log_level", "DEBUG") viper.Set("mysql.ip", "127.0.0.1") viper.Set("mysql.port", 3306) viper.Set("mysql.user", "root") viper.Set("mysql.password", "123456") viper.Set("mysql.database", "awesome") viper.Set("redis.ip", "127.0.0.1") viper.Set("redis.port", 6381) err := viper.SafeWriteConfig() if err != nil { log.Fatal("write config failed: ", err) } } 编译、运行程序,生成的文件如下: app_name = "awesome web" log_level = "DEBUG" [mysql] database = "awesome" ip = "127.0.0.1" password = "123456" port = 3306 user = "root" [redis] ip = "127.0.0.1" port = 6381 监听文件修改 viper 可以监听文件修改,热加载配置。因此不需要重启服务器,就能让配置生效。 package main import ( "fmt" "log" "time" "github.com/spf13/viper" ) func main() { viper.SetConfigName("config") viper.SetConfigType("toml") viper.AddConfigPath(".") err := viper.ReadInConfig() if err != nil { log.Fatal("read config failed: %v", err) } viper.WatchConfig() fmt.Println("redis port before sleep: ", viper.Get("redis.port")) time.Sleep(time.Second * 10) fmt.Println("redis port after sleep: ", viper.Get("redis.port")) } 只需要调用viper.WatchConfig,viper 会自动监听配置修改。如果有修改,重新加载的配置。 上面程序中,我们先打印redis.port的值,然后Sleep 10s。在这期间修改配置中redis.port的值,Sleep结束后再次打印。发现打印出修改后的值: redis port before sleep: 7381 redis port after sleep: 73810 另外,还可以为配置修改增加一个回调: viper.OnConfigChange(func(e fsnotify.Event) { fmt.Printf("Config file:%s Op:%s\n", e.Name, e.Op) }) 这样文件修改时会执行这个回调。 viper 使用fsnotify这个库来实现监听文件修改的功能。 完整示例代码见 GitHub 参考 1. viper GitHub 仓库 这篇文章对您有用吗? 我们要如何帮助您? 发表回复 您的电子邮箱地址不会被公开。 必填项已用*标注
__label__pos
0.732692
Exportfile for AOT version 1.0 or later Formatversion: 1 ***Element: CLS ; Microsoft Dynamics AX Class: SysHelpBookCrossword unloaded ; -------------------------------------------------------------------------------- CLSVERSION 1 CLASS #SysHelpBookCrossword PROPERTIES Name #SysHelpBookCrossword Extends #SysHelpBook RunOn #Client ENDPROPERTIES METHODS Version: 3 SOURCE #development #static server container development() #{ ##AOT # container result; # DocNode docNode = TreeNode::findNode(#SystemFunctionsPath); # TreeNodeIterator iterator = docNode.AOTiterator(); # str text; # #str getDescription(str html) #{ # int i = strscan(html, ' description', 1, strlen(html)); # int j = strscan(html, '', 1, strlen(html)); # int j = strscan(html, ' ', i+1, strlen(html)); # if (!i || !j) # return ''; # return Web::stripHTML(substr(html, i, j-i)); #} # # # if (iterator) # docNode = iterator.next(); # # while (docNode) # { # text = getDescription(docNode.AOTgetSource()); # if (!text) # text = getDescription2(docNode.AOTgetSource()); # if (text) # result += [[docNode.treeNodeName(), 'Which function '+text]]; # # docNode = iterator.next(); # } # # return result; #} ENDSOURCE ENDMETHODS ENDCLASS ***Element: JOB ; Microsoft Dynamics AX Job: MyCrossWordInAX unloaded ; -------------------------------------------------------------------------------- JOBVERSION 1 SOURCE #MyCrossWordInAX #static void MyCrossWordInAX(Args _args) #{ # SysHelpCrosswordEngine crossWord; # # crossWord = new SysHelpCrosswordEngine(); # crossWord.addWord("Zubair","Name of the blogger of daxline.blogspot.com"); # crossWord.addWord("Dynamics AX", "An ERP product by Microsoft"); # crossWord.addWord("New Delhi", "Capital of India"); # crossWord.addWord("Girl interrupted", "Angelina Jolie won an Oscar for her role in which movie"); # crossWord.result(); # crossWord.toHtml2(); #} ENDSOURCE ***Element: JOB ; Microsoft Dynamics AX Job: AXGeneratedCrossword unloaded ; -------------------------------------------------------------------------------- JOBVERSION 1 SOURCE #AXGeneratedCrossword #static void AXGeneratedCrossword(Args _args) #{ # SysHelpBookCrossword crossword; # # crossword = new SysHelpBookCrossword(); # crossword.buildText("://Development"); #} ENDSOURCE ***Element: PRN ; Microsoft Dynamics AX Project : CrossWordInAX unloaded ; -------------------------------------------------------------------------------- PROJECTVERSION 2 PROJECT #CrossWordInAX PRIVATE PROPERTIES Name #CrossWordInAX ENDPROPERTIES PROJECTCLASS ProjectNode BEGINNODE FILETYPE 0 UTILTYPE 45 UTILOBJECTID 5916 NODETYPE 329 NAME #SysHelpBookCrossword ENDNODE BEGINNODE FILETYPE 0 UTILTYPE 5 UTILOBJECTID 0 NODETYPE 215 NAME #MyCrossWordInAX ENDNODE BEGINNODE FILETYPE 0 UTILTYPE 5 UTILOBJECTID 0 NODETYPE 215 NAME #AXGeneratedCrossword ENDNODE ENDPROJECT ***Element: END
__label__pos
0.990417
彻底搞懂Bitmap的内存计算(二) 前言 看了一下近乎彻底搞懂Bitmap的内存计算(一)的发布时间是2019年9月,打死我都没想到第二篇会拖到两年半之后,不管怎样现在补上,在上篇文章中我们总结了Bitmap所占内存空间的计算公式如下: 占用内存 = 图片宽度/inSampleSize*inTargetDensity/inDensity*图片高度/inSampleSize**inTargetDensity/inDensity*每个像素所占的内存 复制代码 接下来我们结合代码一步步分析,代码基于android的API 29。 正文 本文主要分为两个部分,第一部分底层计算每个像素所占的大小,主要介绍底层怎么计算每个像素所占内存的大小,第二部分主要介绍应用层的参数如:inSampleSize、inTargetDensity、inDensity以及图片宽高怎么影响最终生成的Bitmap的大小 底层计算每个像素所占的大小 看下Bitmap的getAllocationByteCount()函数,这个函数返回Bitmap所占内存的大小如下: public final int getAllocationByteCount() { if (mRecycled) { Log.w(TAG, "Called getAllocationByteCount() on a recycle()'d bitmap! " + "This is undefined behavior!"); return 0; } return nativeGetAllocationByteCount(mNativePtr); } 复制代码 走到了nativeGetAllocationByteCount,是个native方法 image.png 作为一个有追求的程序员,怎么能被这个小小的困难吓倒,继续往下肝。找到frameworks/base/libs/hwui/jni/Bitmap.cpp,映射到了如下代码: static jint Bitmap_getAllocationByteCount(JNIEnv* env, jobject, jlong bitmapPtr) { LocalScopedBitmap bitmapHandle(bitmapPtr); return static_cast<jint>(bitmapHandle->getAllocationByteCount()); } 复制代码 继续往下跟到LocalScopedBitmap#getAllocationByteCount(),如下 size_t getAllocationByteCount() const { if (mBitmap) { return mBitmap->getAllocationByteCount(); } return mAllocationSize; } 复制代码 走到Bitmap#getAllocationByteCount(),如下: size_t Bitmap::getAllocationByteCount() const { switch (mPixelStorageType) { case PixelStorageType::Heap: return mPixelStorage.heap.size; case PixelStorageType::Ashmem: return mPixelStorage.ashmem.size; default: return rowBytes() * height(); } } 复制代码 这里可以看到不同的像素存储类型,计算逻辑是不一样的,但是对于最终的结果影响不大,这里简单提一下Bitmap像素数据在内存的存放位置:2.3之前的像素存储需要的内存是在native上分配的,并且生命周期不太可控,可能需要用户自己回收。 2.3-7.1之间,Bitmap的像素存储在Dalvik的Java堆上对应PixelStorageType::Heap,当然,4.4之前的甚至能在匿名共享内存上分配(Fresco采用)对应PixelStorageType::Ashmem,而8.0之后的像素内存又重新回到native上去分配,不需要用户主动回收,8.0之后图像资源的管理更加优秀,极大降低了OOM。本文基于API29,也就是Android 10,因此对应的是默认逻辑rowBytes() * height(),也就是每行占的内存乘以高度,继续跟到了external/skia/include/core/SkPixelRef.h#rowBytes(),如下: size_t rowBytes() const { return fRowBytes; } 复制代码 看下fRowBytes在哪里赋值: void SkPixelRef::android_only_reset(int width, int height, size_t rowBytes) { fWidth = width; fHeight = height; fRowBytes = rowBytes; this->notifyPixelsChanged(); } 复制代码 再看下android_only_reset的调用链路, void Bitmap::reconfigure(const SkImageInfo& newInfo, size_t rowBytes) { mInfo = validateAlpha(newInfo); // TODO: Skia intends for SkPixelRef to be immutable, but this method // modifies it. Find another way to support reusing the same pixel memory. this->android_only_reset(mInfo.width(), mInfo.height(), rowBytes); } 复制代码 再看下 reconfigure 的调用链路,如下: void Bitmap::reconfigure(const SkImageInfo& info) { reconfigure(info, info.minRowBytes()); } 复制代码 发现rowBytes()最终是 SkImageInfo 中的 minRowBytes() 计算的,继续跟踪external/skia/include/core/SkImageInfo.h: size_t minRowBytes() const { uint64_t minRowBytes = this->minRowBytes64(); if (!SkTFitsIn<int32_t>(minRowBytes)) { return 0; } return (size_t)minRowBytes; } 复制代码 继续肝到了minRowBytes64(),如下: uint64_t minRowBytes64() const { return (uint64_t)sk_64_mul(this->width(), this->bytesPerPixel()); } 复制代码 意思就是图片宽度乘以每个像素占的字节,看下bytesPerPixel(),如下: int bytesPerPixel() const { return fColorInfo.bytesPerPixel(); } 复制代码 到了SkColorInfo#bytesPerPixel()如下: int SkColorInfo::bytesPerPixel() const { return SkColorTypeBytesPerPixel(fColorType); } 复制代码 继续SkColorTypeBytesPerPixel 如下: int SkColorTypeBytesPerPixel(SkColorType ct) { switch (ct) { case kUnknown_SkColorType: return 0; case kAlpha_8_SkColorType: return 1; case kRGB_565_SkColorType: return 2; case kARGB_4444_SkColorType: return 2; case kRGBA_8888_SkColorType: return 4; case kBGRA_8888_SkColorType: return 4; case kRGB_888x_SkColorType: return 4; case kRGBA_1010102_SkColorType: return 4; case kRGB_101010x_SkColorType: return 4; case kBGRA_1010102_SkColorType: return 4; case kBGR_101010x_SkColorType: return 4; case kGray_8_SkColorType: return 1; case kRGBA_F16Norm_SkColorType: return 8; case kRGBA_F16_SkColorType: return 8; case kRGBA_F32_SkColorType: return 16; case kR8G8_unorm_SkColorType: return 2; case kA16_unorm_SkColorType: return 2; case kR16G16_unorm_SkColorType: return 4; case kA16_float_SkColorType: return 2; case kR16G16_float_SkColorType: return 4; case kR16G16B16A16_unorm_SkColorType: return 8; } SkUNREACHABLE; } 复制代码 到这里,豁然开朗,其实底层对于每个像素所占的字节是和颜色相关的,和应用层的Bitmap.Config是一一对应,列了一张常用的几个对应表格如下: 应用层名称底层名称位数所占内存 ALPHA_8kAlpha_8_SkColorType81 RGB_565kRGB_565_SkColorType162 ARGB_4444kARGB_4444_SkColorType162 ARGB_8888kBGRA_8888_SkColorType324 到此我们知道了 Bitmap.Config中的颜色空间 是如何影响底层计算单个像素内存的逻辑。 应用层参数影响底层Bitmap的尺寸 先上公式: 占用内存 = 图片宽度/inSampleSize*inTargetDensity/inDensity*图片高度/inSampleSize**inTargetDensity/inDensity*每个像素所占的内存 复制代码 从如下代码出发: Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.banner); 复制代码 最终到了BitmapFactory#decodeResourceStream(),如下: @Nullable public static Bitmap decodeResourceStream(@Nullable Resources res, @Nullable TypedValue value, @Nullable InputStream is, @Nullable Rect pad, @Nullable Options opts) { validate(opts); if (opts == null) { opts = new Options(); } if (opts.inDensity == 0 && value != null) { //注释1 final int density = value.density; if (density == TypedValue.DENSITY_DEFAULT) { opts.inDensity = DisplayMetrics.DENSITY_DEFAULT; } else if (density != TypedValue.DENSITY_NONE) { opts.inDensity = density; } } //注释2 if (opts.inTargetDensity == 0 && res != null) { opts.inTargetDensity = res.getDisplayMetrics().densityDpi; } return decodeStream(is, pad, opts); } 复制代码 这里面出现了计算公式里面的inDensity和inTargetDensity,从注释2中可以看到 inTargetDensity 值为res.getDisplayMetrics().densityDpi,和设备相关,我手里的手机是1920*1080的值为480,从注释1看出opts.inDensity的值来自于value.density,这个value是从如下代码里面计算传值的: public static Bitmap decodeResource(Resources res, int id, Options opts) { validate(opts); Bitmap bm = null; InputStream is = null; try { final TypedValue value = new TypedValue(); //注释1 is = res.openRawResource(id, value); bm = decodeResourceStream(res, value, is, null, opts); } catch (Exception e) { /* do nothing. If the exception happened on open, bm will be null. If it happened on close, bm is still valid. */ } finally { try { if (is != null) is.close(); } catch (IOException e) { // Ignore } } if (bm == null && opts != null && opts.inBitmap != null) { throw new IllegalArgumentException("Problem decoding into existing bitmap"); } return bm; } 复制代码 看注释1,进入Resources#openRawResource(),最终跟到 @NonNull public InputStream openRawResource(@RawRes int id, TypedValue value) throws NotFoundException { return mResourcesImpl.openRawResource(id, value); } 复制代码 openRawResource会根据资源缩放的位置对TypedValue的inDensity赋值,这里不深究,有时间单开一篇去讲,具体结果如下图: image.png 回过头了看BitmpaFactory的逻辑,最终会走到如下代码: private static native Bitmap nativeDecodeStream(InputStream is, byte[] storage, Rect padding, Options opts, long inBitmapHandle, long colorSpaceHandle); 复制代码 又是个native方法,最终跟到frameworks/base/libs/hwui/jni/BitmapFactory.cpp#doDecode函数,代码较多,精简部分,只留下关键代码如下代码: static jobject doDecode(JNIEnv* env, std::unique_ptr<SkStreamRewindable> stream, jobject padding, jobject options, jlong inBitmapHandle, jlong colorSpaceHandle) { sampleSize = env->GetIntField(options, gOptions_sampleSizeFieldID); // Correct a non-positive sampleSize. sampleSize defaults to zero within the // options object, which is strange. //注释1 修正sampleSize if (sampleSize <= 0) { sampleSize = 1; } if (env->GetBooleanField(options, gOptions_scaledFieldID)) { //注释2获取density 因为图片是放在drawable文件夹下面,density等于160 const int density = env->GetIntField(options, gOptions_densityFieldID); //注释3 获取targetDensity targetDensity等于160 const int targetDensity = env->GetIntField(options, gOptions_targetDensityFieldID); //注释4 screenDensity等于0 const int screenDensity = env->GetIntField(options, gOptions_screenDensityFieldID); if (density != 0 && targetDensity != 0 && density != screenDensity) { // 注释5 scale 等于3 scale = (float) targetDensity / density; } } //注释6 根据Options.inSampleSize技术输出的尺寸 SkISize size = codec->getSampledDimensions(sampleSize); //注释7 根据前面的density和targetDensity计算出的scale,再次计算缩放的宽高 if (scale != 1.0f) { willScale = true; scaledWidth = static_cast<int>(scaledWidth * scale + 0.5f); scaledHeight = static_cast<int>(scaledHeight * scale + 0.5f); } if (options != NULL) { jstring mimeType = getMimeTypeAsJavaString(env, codec->getEncodedFormat()); if (env->ExceptionCheck()) { return nullObjectReturn("OOM in getMimeTypeAsJavaString()"); } // 注释8 往java写入最终的宽高 env->SetIntField(options, gOptions_widthFieldID, scaledWidth); env->SetIntField(options, gOptions_heightFieldID, scaledHeight); env->SetObjectField(options, gOptions_mimeFieldID, mimeType); jint configID = GraphicsJNI::colorTypeToLegacyBitmapConfig(decodeColorType); if (isHardware) { configID = GraphicsJNI::kHardware_LegacyBitmapConfig; } jobject config = env->CallStaticObjectMethod(gBitmapConfig_class, gBitmapConfig_nativeToConfigMethodID, configID); env->SetObjectField(options, gOptions_outConfigFieldID, config); env->SetObjectField(options, gOptions_outColorSpaceFieldID, GraphicsJNI::getColorSpace(env, decodeColorSpace.get(), decodeColorType)); if (onlyDecodeSize) { return nullptr; } } return bitmap;搞 } 复制代码 注释1处获取修正 Options.inSampleSize,注释2注释3注释4注释5通过获取的Options的targetDensity、density计算出scale,注释6根据Options.inSampleSize技术输出的尺寸,注释7注释8通过之前计算的scale计算出输出Bitmap最终的宽高,输出Bitmap尺寸的宽高计算尺寸公式: 输出BitMap宽*高 = 图片宽度/inSampleSize*inTargetDensity/inDensity*图片高度/inSampleSize**inTargetDensity/inDensity 复制代码 加上上一节底层计算每个像素的大小,最后得到公式如下: 占用内存 = 图片宽度/inSampleSize*inTargetDensity/inDensity*图片高度/inSampleSize**inTargetDensity/inDensity*每个像素所占的内存 复制代码 至此Bitmap占用内存计算从上层到底层算是撸了个遍 总结 本文承接上文,时间跨度达两年多之久,主要是设计到Native测的代码晦涩难懂,费时费力,加上换了新工作,All in 业务,时间和精力有限,能在新的一年的年初补上欠账,走出舒适区,尝试自己未曾经历过的事情,也算是一份新年礼物,大家共勉,程序员永不为奴,奥利给 分类: Android 标签:
__label__pos
0.985234
1. CSS 2. Flash 3. HTML 4. Illustrator 5. Java 6. JavaScript 7. Maya 8. Photography 9. Photoshop 10. PHP 11. Ruby 12. Ruby on Rails 13. 3ds Max CSS: CSS: How to use Overflow 1. Clicks today: 0 2. Clicks this month: 0 3. Overall rating: 4.00/5 CSS » Tips and Tricks — almost 13 years ago The element 'Overflow' is a tricky one and this guide will help you. This article will give examples and explanations are included. Comments Your Comment You must be logged in to post a comment.
__label__pos
0.998599
科举小抄 科举小抄 - 阿里云大学“科考”辅助工具 // ==UserScript== // @name 科举小抄 // @namespace https://github.com/fuckKeju/fuckKeju // @version 0.0.5 // @description 科举小抄 - 阿里云大学“科考”辅助工具 // @author fuckKeju // @match *.developer.aliyun.com/* // @run-at document-start // @grant unsafeWindow // ==/UserScript== /* 题库数据 */ var customQuestionsDatabase = [] var useCustomQuestionsDatabase = false async function getPageWindow () { return new Promise(function (resolve, reject) { if (window._pageWindow) { return resolve(window._pageWindow) } const listenEventList = ['load', 'mousemove', 'scroll', 'get-page-window-event'] function getWin (event) { window._pageWindow = this // debug.log('getPageWindow succeed', event) listenEventList.forEach(eventType => { window.removeEventListener(eventType, getWin, true) }) resolve(window._pageWindow) } listenEventList.forEach(eventType => { window.addEventListener(eventType, getWin, true) }) /* 自行派发事件以便用最短的时候获得pageWindow对象 */ window.dispatchEvent(new window.Event('get-page-window-event')) }) } getPageWindow() /* 修正标题字符串 */ function trimTitle (title, removeSerialNumber) { title = title || '' title = title.replace(/\s+/gi, ' ').replace(/\?{2,}/gi, ' ') if (removeSerialNumber) { title = title.replace(/^\d+\./, '') } return title } /* 提取答案字符串 */ function fixAnswer (answer) { answer = answer || '' return answer.replace(/^[A-Za-z]\.\s/, '').replace(/\s+--checked/, '') } /** * 判断两条题目是否为同一条题目 * @param questionA * @param questionB */ function isTheSameQuestion (questionA, questionB) { let isSame = true const titleA = trimTitle(questionA.title, true) const titleB = trimTitle(questionB.title, true) if (titleA === titleB) { for (let i = 0; i < questionA.answerList.length; i++) { const answerA = fixAnswer(questionA.answerList[i]) let hasSameAnswer = false for (let j = 0; j < questionB.answerList.length; j++) { const answerB = fixAnswer(questionB.answerList[j]) if (answerA === answerB) { hasSameAnswer = true break } } if (!hasSameAnswer) { isSame = false break } } } else { isSame = false } // isSame && console.log(titleA, titleB, isSame) return isSame } /* 因为收集了部分异常数据,为了排查异常数据的干扰,所以需要进行是否异常的判断 */ function isNormalQuestion (question) { return /\s+--checked/.test(JSON.stringify(question.answerList)) } function eachQuestionsDatabase (questionsDatabase, callback) { questionsDatabase.forEach((items, index) => { if (Array.isArray(items)) { items.forEach(curQuestion => { callback(curQuestion, index) }) } else { callback(items, index) } }) } function getQuestionsDatabase () { const subjectEl = document.querySelector('.yq-main-examination .top-info h2.title-content') let questionsDatabase = [] try { if (subjectEl) { questionsDatabase = JSON.parse(localStorage.getItem(subjectEl.innerText) || '[]') } else { questionsDatabase = customQuestionsDatabase } } catch (e) { questionsDatabase = [] } return questionsDatabase } /* 从混乱的题库集里提取整理后的题库 */ function extractQuestionList (questionsDatabase) { const questionList = [] let addCount = 0 function addToQuestionList (question) { addCount++ // console.log(question, addCount) if (!question || !question.title || !Array.isArray(question.answerList)) { return false } let hasSameQuestion = false for (let i = 0; i < questionList.length; i++) { const questionB = questionList[i] if (isTheSameQuestion(question, questionB)) { hasSameQuestion = true if (isNormalQuestion(question) && question.rightAnswer === '答案正确') { questionList[i] = question } else { questionList[i].relatedQuestions = questionList[i].relatedQuestions || [] questionList[i].relatedQuestions.push(question) } break } } if (!hasSameQuestion) { questionList.push(question) } } eachQuestionsDatabase(questionsDatabase, (question, index) => { addToQuestionList(question, index) }) return questionList } // console.log(extractQuestionList(customQuestionsDatabase)) /** * 从某个题库数据集里查找是否存在相关的题目 * @param questionsDatabase * @param questions */ function searchRelatedQuestions (questionsDatabase, questions) { let relatedQuestions = [] eachQuestionsDatabase(questionsDatabase, (questionsA) => { if (isTheSameQuestion(questionsA, questions)) { relatedQuestions.push(questionsA) } }) /* 查找是否存在答对的历史记录,优先显示答对的数据 */ if (relatedQuestions.length > 1) { const rightAnswerArr = [] const wrongAnswerArr = [] relatedQuestions.forEach(question => { if (question.rightAnswer === '答案正确' && isNormalQuestion(question)) { rightAnswerArr.push(question) } else { wrongAnswerArr.push(question) } }) relatedQuestions = rightAnswerArr.concat(wrongAnswerArr) } return relatedQuestions } /** * 判断某条题目的相关问答库里是否包含一样的答案记录 * @param questions * @param relatedQuestions */ function hasTheSameQuestionsInRelatedQuestions (questions, relatedQuestions) { let hasSame = false relatedQuestions = relatedQuestions || [] for (let i = 0; i < relatedQuestions.length; i++) { const relatedQuestion = relatedQuestions[i] let isSame = true for (let j = 0; j < relatedQuestion.answerList.length; j++) { const answer = relatedQuestion.answerList[j] const relatedQuestionChecked = /\s+--checked/.test(answer) const questionsChecked = /\s+--checked/.test(questions.answerList[j]) if (relatedQuestionChecked !== questionsChecked) { isSame = false break } } if (isSame) { hasSame = true break } } return hasSame } /** * 遍历页面上的题目并进行回调,该方法必须在试题页面才能运行 * @param callback * @returns {[]} */ function eachQuestionItem (callback) { const result = [] const isExamMode = document.querySelector('.yq-main-examination .time-info') const items = document.querySelectorAll('.question-panel .question-item') if (items) { items.forEach(questionItemEl => { const type = questionItemEl.querySelector('.q-title .q-tag').innerText.trim() const title = trimTitle(questionItemEl.querySelector('.q-title .q-t-text').innerText.trim()) const answerList = [] const answerListEl = questionItemEl.querySelectorAll('.q-option .answer-text') answerListEl.forEach(answerEl => { let answer = answerEl.innerText.trim() const checkedEl = answerEl.parentNode.querySelector('input') if (checkedEl && checkedEl.checked) { answer += ' --checked' } answerList.push(answer) }) const questionObj = { title, type, answerList } const pointEl = questionItemEl.querySelector('.e-point .p-detail') if (pointEl) { questionObj.point = '相关知识点:' + pointEl.innerText.trim() } else { questionObj.point = '未匹配到任何相关知识点' } const rightAnswerEl = questionItemEl.querySelector('.right-answer') if (rightAnswerEl) { questionObj.rightAnswer = rightAnswerEl.innerText.trim() || '答案正确' } else { if (isExamMode) { questionObj.rightAnswer = '答案未知' } else { questionObj.rightAnswer = '答案正确' } } result.push(questionObj) if (callback instanceof Function) { try { callback(questionObj, questionItemEl) } catch (err) { console.error('eachQuestionItem error:', err, questionObj, questionItemEl) } } }) } return result } /* 添加相关题目内容到题目面板下面,并且添加显示隐藏事件 */ function addRelatedQuestionsDom (questionItemEl, relatedQuestions) { const dd = document.createElement('dd') dd.setAttribute('class', 'relatedQuestions') dd.style.marginTop = '30px' dd.style.display = 'none' dd.style.border = '1px solid #ccc' dd.style.borderRadius = '5px' // dd.style.padding = '10px' // dd.style.backgroundColor = '#f9f9f9' if (questionItemEl.querySelector('.relatedQuestions')) { questionItemEl.removeChild(questionItemEl.querySelector('.relatedQuestions')) } if (relatedQuestions.length) { const codeEl = document.createElement('pre') codeEl.style.border = 'none' codeEl.innerHTML = JSON.stringify(relatedQuestions, null, 2) dd.appendChild(codeEl) questionItemEl.appendChild(dd) } else { dd.innerText = '暂无相关题目信息,先考几遍,然后查看考试结果再试试吧' questionItemEl.appendChild(dd) } questionItemEl.ondblclick = function (event) { const relatedQuestions = questionItemEl.querySelector('.relatedQuestions') if (relatedQuestions) { if (relatedQuestions.style.display === 'none') { relatedQuestions.style.display = 'block' relatedQuestions.style.opacity = 0.4 relatedQuestions.style.overflow = 'auto' relatedQuestions.style.maxHeight = '200px' } else { relatedQuestions.style.display = 'none' } } } } /** * 自动匹配题目并尝试自动填充对应答案 * @param questionsDatabase */ function autoMatchQuestionAndCheckedAnswer (questionsDatabase) { eachQuestionItem((questions, questionItemEl) => { const relatedQuestions = searchRelatedQuestions(questionsDatabase, questions) if (relatedQuestions.length) { const relatedQuestion = relatedQuestions[0] if (isNormalQuestion(relatedQuestion) && relatedQuestion.rightAnswer === '答案正确') { relatedQuestion.answerList.forEach((answer, index) => { if (/\s+--checked/.test(answer)) { const answerLabel = questionItemEl.querySelectorAll('label.option-label') if (answerLabel[index]) { answerLabel[index].click() } } }) } } else { console.log('以下题目无法匹配答案:', questions, questionItemEl, relatedQuestions) } }) } /* 隐藏相关题目面板 */ function hideRelatedQuestions () { const relatedQuestionsEls = document.querySelectorAll('.relatedQuestions') relatedQuestionsEls.forEach(item => { item.style.display = 'none' }) } let hasInit = false async function fuckKeju () { if (hasInit) { return false } console.log('科举小抄 init suc') hasInit = true const subjectTitle = document.querySelector('.yq-main-examination .top-info h2.title-content').innerText const isExamMode = document.querySelector('.yq-main-examination .time-info') let questionsDatabase = getQuestionsDatabase() /* 使用预置数据,而非定义的数据 */ if (useCustomQuestionsDatabase) { questionsDatabase = customQuestionsDatabase } let findNewQuestion = false const curQuestionsList = eachQuestionItem((questions, questionItemEl) => { const relatedQuestions = searchRelatedQuestions(questionsDatabase, questions) addRelatedQuestionsDom(questionItemEl, relatedQuestions) /* 收集新题目数据 */ if (!isExamMode && !hasTheSameQuestionsInRelatedQuestions(questions, relatedQuestions)) { findNewQuestion = true questionsDatabase.push(questions) if (findNewQuestion) { console.log('发现新的题目,或新的答案记录:', questions) } } }) /* 提示到控制面板,用于手动收集题目数据 */ console.log(JSON.stringify(curQuestionsList, null, 2)) /* 重新写入收集到的题目数据 */ if (findNewQuestion) { // localStorage.setItem(subjectTitle, JSON.stringify(questionsDatabase)) } localStorage.setItem(subjectTitle, JSON.stringify(questionsDatabase)) /* 考试模式下双击标题尝试自填充答案 */ const subjectEl = document.querySelector('.yq-main-examination .top-info h2.title-content') subjectEl.ondblclick = function () { if (isExamMode) { autoMatchQuestionAndCheckedAnswer(questionsDatabase) } } /* 切换题目时候,隐藏小抄 */ const switchDoms = document.querySelectorAll('.question-num span.item') const switchDoms02 = document.querySelectorAll('.e-opt-panel a') switchDoms.forEach(el => { el.onmouseenter = hideRelatedQuestions }) switchDoms02.forEach(el => { el.onclick = hideRelatedQuestions }) /* 通过控制面板提取题库 */ const pageWindow = await getPageWindow() pageWindow.extractQuestionList = function (print) { const questionsDatabase = getQuestionsDatabase() const questionList = extractQuestionList(questionsDatabase) if (print) { console.log(JSON.stringify(questionList, null, 2)) } return questionList } } function ready (selector, fn, shadowRoot) { const listeners = [] const win = window const doc = shadowRoot || win.document const MutationObserver = win.MutationObserver || win.WebKitMutationObserver let observer function $ready (selector, fn) { // 储存选择器和回调函数 listeners.push({ selector: selector, fn: fn }) if (!observer) { // 监听document变化 observer = new MutationObserver(check) observer.observe(shadowRoot || doc.documentElement, { childList: true, subtree: true }) } // 检查该节点是否已经在DOM中 check() } function check () { for (let i = 0; i < listeners.length; i++) { var listener = listeners[i] var elements = doc.querySelectorAll(listener.selector) for (let j = 0; j < elements.length; j++) { var element = elements[j] if (!element._isMutationReady_) { element._isMutationReady_ = true listener.fn.call(element, element) } } } } $ready(selector, fn) } ready('.question-panel .question-item', () => { /** * 此处必须延迟执行,题目渲染和选中渲染是异步操作 * 需要延时等待选中的渲染成功才执行初始化逻辑 */ console.log('检查到进入了试题页面,即将为你初始化小抄逻辑') setTimeout(function () { fuckKeju() }, 1000 * 3) })
__label__pos
0.999985
THE IMPORTANCE OF SAMPLING DISTRIBUTIONS AND STANDARD ERRORS Stats Assignment Homework Help THE IMPORTANCE OF SAMPLING DISTRIBUTIONS AND STANDARD ERRORS Statistical inference is based on sampling distributions. If you are not certain  ..iat you understand what a sampling distribution is, now is the time to re-.Iew Section 9.6. When you understand what the sampling distribution of the mean is, it is easy to understand other sampling distributions, such as the distribution of p in Section 9.11. Different sampling distributions have different formulas for computing the standard error. You have learned two such formulas, which we will use extensively. They are Untitled Again, if you are not certain that you understand what U;r is, now is the time to review Section 9.7. When you understand what U;r is, it is easy to understand the meaning of other standard errors, such as Ufi. We will need standard error formulas as we go on. Each will be given when the n ed for it arises. PROBLEM 1. (Note: You do not have to compute sampling distributions to solve problems. However, the best way to make sure you understand the concept is to compute a sampling distribution.) Given the population 2 4 8 8 10 10 (a) How many samples of size n = 2 can be drawn from the population? (b) Compute and tabulate the sampling distribution of the mean for samples of size n = 2. 2. (a) What does O”x mean? ( b) What does O”~mean? (c) For a given population,which is larg,er, O”x or O”x? 3. The Dow Jones industrial average is an average of the prices of 30stocks. The average varies from day to day. Suppose 100 stocks were used in computing the average. Would you expect the 100-priceaverage to have greater or smaller variations than the 30-priceaverage? Why? .4. The Palm Tree Vacation Resort advertises that it has ideal weather with an average (mean) temperature of 70°F. In a random sample of 35 days,  what is the probability that Il.lean temperature will be 68°F or lower ifthe standard deviation of daily temperatures is 4 degrees? (b) degrees? 5. An automatic machine made by Global Dispensers pours an average 6. The mean number of Synchrons sold by Synchronics, Inc., is 210 per – day, and the standard deviation is 30 Synchrons per day. In a random sample of 36 selli~g days, what is the probability that mean’ daily Synchron sales will be 200 or more?  7. A quality-control inspector for National Shafts checks automatic machine operations in National’s manufacturing plant. One machine has een set to make shafts that are supposed to have a diameter of 50 mm (millimeter). Machine output is normally distributed, and shaft diameters have a standard deviation of 0.02 mm. Periodically, the inspector selects a random sample of tour shafts, measures them, and then computes the sample mean diameter. If the sample average is below  49.98 mm, or above 50.02 mm, the inspector has the machine stopped. and reset. Suppose the mean diameter of shafts being produced is 50 mm. What is the probability that, after computtng a sample mean, the operator will have to reset the machine?  8. Gen Green, an executive of the United Manufacturers Association,wants to estimate the mean daily wage in a large industry by using the mean wage of a random sample of 100 workers. Gen’s objective is tohave the s Ie mea’ he1ifcJu t mean by $1 or.less. If the standard deviation of daily wages is $4 per day, w at is the probability that Gen achieves her objective 9. Wheat Products has appropriated funds to sample Massachusetts (population about 5 million) and Rhode Island (population about 1 million) to estimate average (mean) product .consumption for each state. It is assumed that product consumption variability O”x is the same for each state. Money is available to optain a total sample size of 1200. Suppose the sample is proportioned’S to 1, as are the state populations. a) What will be the sample size for each state? (b) After the samples SUMMARY A random sample is a sample selected in a way such that every element in the population has a known chancenot zero, of being included in the sample. In a simple random sample df size n, (1) every element in the population has an equal probability of being included in the sample,’ and (2) every sample of size n has an equal probability of being the selected sample. In a systematic random sample, every itelement in the population IS selected; the starting point in the first i elements is obtained randomly. Posted on August 29, 2014 in SAMPLING METHOD AND SAMPLING DISTRIBUTION Share the Story About the Author Back to Top Share This
__label__pos
0.998865
JavaScript must be enabled. The Standards | Northstar Digital Literacy Assessment Tool - Free Online Assessment Tool for Educators and Community-Based Organizations   Northstar Digital Literacy Assessment Tool Log The Standards Basic Computer Skills Mac OS X World Wide Web Email Windows Word Download PDF Version Basic Computer Skills 1. Distinguish between desktop and laptop computers. 2. Identify specific computer hardware: a system unit, monitor, printer, keyboard, mouse or touchpad, USB port 3. Turn computer and monitor on and off 4. Log on to computer 5. Demonstrate knowledge of function and placement of keys on keyboard: Enter, Shift, Control, Backspace, Delete, Arrow Keys, Tab, Caps Lock, Number Lock 6. Identify types of mice: mouse and touchpad 7. Identify mouse pointer shapes and match them to the correct context of use: typing arrow (text), arrow (basic clicking), hand pointer (clickable links) 8. Demonstrate appropriate use and ability to right-click and left-click 9. Double click and right click 10. Drag and drop 11. Use mouse to select check boxes, use drop-down menus and scroll 12. Adjust volume and mute audio 13. Plug in headphones correctly and use when appropriate 14. Identify icons on desktop (Internet Browser, Control Panel, Recycle Bin, Skype) 15. Demonstrate the ability to use the recycle bin correctly for trashing and retrieving items 16. Demonstrate understanding that it is possible to customize a computer for increased accessibility 17. Demonstrate understanding that mice can be customized for left-handed people and that the speed of clicking can also be customized 18. Demonstrate understanding that screen resolution can be changed 19. Demonstrate understanding that software programs are upgraded periodically and that different versions may be installed on different computers 20. Identify storage media: USB/Flash drives (external) and hard drive (external and internal) World Wide Web 1. Identify an Internet Service Provider and identify the main options for connecting to the internet: Dial-up, High Speed (cable or DSL), or wireless connection. 2. Identify commonly used browsers (Internet Explorer, Firefox, Chrome, Safari) and demonstrate knowledge of function. 3. Identify the address bar and enter a URL address. 4. Identify a website. 5. Identify a homepage. 6. Identify the following browser toolbar buttons and demonstrate the ability to use them: home, refresh, stop, back, forward 7. Use scroll bars to view different portions of webpages 8. Identify a hyperlink and demonstrate the ability to use a hyperlink to access other webpages. 9. Create a new tab, open a webpage in a tab, and move between tabs. 10. Enlarge the displayed text size 11. Fill out an online form. 12. Correctly enter CAPTCHA security codes. 13. Use zoom function to enlarge image (CTRL+ or CTRL-) 14. Identify search engines (Google, Yahoo!, Bing) and enter search terms into the search engine. 15. Identify pop-up windows and close them. 16. Identify pop up windows have been blocked and enable individual pop up windows as needed 17. Identify common domain types: com, org, gov, edu. 18. Demonstrate knowledge that there are ways to increase Internet safety for children. 19. Identify antivirus software providers and function of antivirus software (Norton, McAfee, AVG). 20. Avoid providing personal or financial information unless on a secured website (https://) Windows 1. Identify the operating system used by a computer. 2. Shutdown, restart, and log off a computer. 3. Open, close and switch between windows 4. Minimize and maximize windows 5. Identify the toolbar and menus. 6. Identify the taskbar. 7. Start, and exit programs (Microsoft Word, Excel, PowerPoint) 8. Identify drives on a computer: CD/DVD, floppy, hard drive (C), USB port, network drives (A, B, D, F, H, etc.) 9. Access the help menu. 10. Identify the desktop. 11. Demonstrate knowledge of Windows file organizational system and use it to locate files/documents (desktop, My Document, My Computer) 12. Use "Search" to locate a file or document 13. Delete documents or files. 14. Open programs. 15. Identify basic office software programs (Microsoft Word, Excel, Powerpoint), demonstrate knowledge of their functions, and identify their corresponding file extensions. 16. Open files using appropriate programs Mac OS X 1. Identify the operating system. 2. Identify the Dock. 3. Identify the Menu Bar. 4. Identify the desktop. 5. Use Finder to locate files, folders, and applications. 6. Move and delete documents or files. 7. Identify devices on a computer. 8. Open applications using the Application Folder. 9. Minimize and expand windows. 10. Open applications using the Dock. 11. Close and switch between applications. 12. Quit an application. 13. Demonstrate knowledge of System Preferences. 14. Demonstrate knowledge of Dashboard. 15. Use the help menu. 16. Use "Spotlight" to locate a document. 17. Log out and shutdown a computer. Email 1. Define: email 2. Register for new email account in online program 3. Create username and secure password 4. Log into email 5. Create an email message 6. Address an email, including to more than one recipient 7. Send an email 8. Open an email 9. Reply to only the sender of an email or to all recipients (reply all) 10. Forward an email 11. Add an attachment to an email 12. Open an attachment in an email 13. Move or delete an email and retrieve an email from the trash 14. Understand basics of email etiquette: don't use all capital letters, fill in the subject line, use appropriate greetings & closings 15. Use caution when opening an email from an unfamiliar or unexpected source and avoid opening suspicious attachments 16. Avoid giving out personal information (especially financial information) or email address to unfamiliar people 17. Identify and delete junk mail, including spam 18. Be selective and cautious about forwarding email to large groups of people 19. Define: Computer virus 20. Define and tell the difference between a URL and an email address (see World Wide Web) Word 1. Create a new document 2. Save and close a document 3. Open existing document 4. Identify ribbon and toolbars 5. Demonstrate knowledge of the difference between "Save" and "Save As" functions. 6. Use Save As to save to a particular folder or file location and name the document. 7. Use undo and redo arrows 8. Cut, copy and paste 9. Use spell check and grammar check 10. Format the size, color and type of font 11. Align text: left, center and right justify 12. Set single or double spacing 13. Use bullets and automatic numbering 14. Use print preview and print. 15. Set margins 16. Select portrait or landscape 17. Identify file extensions, corresponding document types and associated programs used to open them: pdf, xls, doc, docx, rtf, pub, ppt, pptx   ↑ Back to Top
__label__pos
0.995153
828..running amuck Discussion in 'Recording' started by chris lannon, Jun 9, 2001. Tags: 1. chris lannon chris lannon Guest Having a bitch of a time with an iBook and the 828 50% success on STARTUP with the 828 connected and powered up :mad: When it runs it's fine..haven't checked the spdf yet tho' Opus..is there and NEC chip in that IBook??? and have you seen the Mobile i/o yet?   2. Opus2000 Opus2000 Well-Known Member Joined: Apr 7, 2001 Chris.. decided to check this part of the forum out and saw your question to me...I'm not to sure what chipset is in the ibook and if it really is relevant or not. I would contact MOTU about that one..that is if you can!! Busy signal all the time usually! I'm wondering if you have a defective unit or a bad firewire cable. I've seen that happen once or twice before. How long ago did you get the 828? You might want to contact the place you got it to see if you can exchange it if you cant get in touch with MOTU Opus   Similar Threads 1. Murdock Replies: 4 Views: 1,955 2. innergalactic Replies: 1 Views: 774 3. Nicpaerez Replies: 1 Views: 1,277 4. oneano Replies: 5 Views: 2,181 5. Darin_god Replies: 2 Views: 1,055 Loading... Share This Page
__label__pos
0.540303
Home » Uncategorized » Augmented Reality and history Augmented Reality and history Just a brief post this time, since I’m still trying to write the conclusion to the book and don’t want to be too distracted, but here’s a thought: … virtual worlds help to redefine what our notion of history actually is. Understanding what translates from the physical world to the virtual world when buildings with which we have an historical relationship are reproduced within a computer-generated environment leads to questions about our experiences and how these become associated with space. In part the new virtual builds may recall our own personal historical connection with the physical version of the building, but our emotional connection with that space is probably at one remove if we are just observing it within the virtual world. However, it is possible to imbue virtual spaces with their own history, through the design of activities, such as in Ian Upton’s Ritual Circles, to foster these experiences and through the actions of people exploring, using and attributing meaning to those spaces under their own auspices. The different nature of the various Globe Theatres within Second Life is testament to that, in that some, though less historically accurate, are located within community spaces and so have a historical significance to the community in which they are embedded, others which are historically accurate survive as showcases of the building skills and interests of its creators, and others are no longer in Second Life and now only exist as 3D models and photographs. As we move more towards using virtual spaces, and in meaning being accrued to physical spaces via augmented realities, will history itself become a more fluid concept? As people modify the augmented aspect of buildings through their own adding of geotagged paradata, will this augmented aspect be considered part of the intrinsic historical meaning of a site, in the same way that a Banksy graffito is preserved and lauded in the physical world at present, or merely ephemeral or a nuisance? As different applications layer different paradata onto sites, will the history of spaces diverge, depending on whether you follow an Apple or an Android historical perspective? And a final thought: Through augmented reality, the mingling of avatars and physical bodies, as pioneered in the Extract Insert installation, will become more commonplace. The worlds through which we move will become tagged with paradata and the wider psychological immersion that comes with understanding a space will be greater. This will have its bigger impact, potentially, in those fourth places within the physical world. Places of ritual significance, performance spaces and game spaces are all those that possess greater semiotic significance and benefit from having that wealth of meaning made manifest.  As paradata are tagged to the artefacts and people around us, then boundary objects become more accessible and the other members in our communities become more known to us. If we can enter these spaces projecting our avatars to others, through mapping them onto our physical bodies, identity becomes more malleable and roleplay more attainable. Potentially new types of spaces will arise, with new conventions and new ways to communicate as the affordances of both worlds collide and create a new synthesis. Those of us who can will live constantly in a state of metaxis. Those who cannot adapt will become increasingly alienated and isolated. Advertisement 5 thoughts on “Augmented Reality and history 1. So does that mean artefacts also have identity and presence? Reminds me of Actor Network Theory and the concept of actants and non-actants interacting. Also James Wersche’s work on the notion that everything is socio-culturally located, i.e. has a history. 2. No I didn’t mean that, but only because I’m not familiar enough with ANT. 🙂 I’d say bots and AI definitely have identity and presence in the way I mean it, and am presenting a paper on how bots have social presence at EDMEDIA and am doing a workshop on identifying the degree to which learners experience copresence with bots next month. I’m not too sure whether I’d be comfortable with talking about simple artefacts having identity, because that implies something more sophisticated and nuanced to me than simply design and its connotations. Similarly a chair has a presence, in that i can see it’s there, but this is a very much downgraded version of the idea of social presence. And they can’t have self-presence can they? Maybe we’re talking about something more like design-enhanced characteristics (DEC). But then I’ve never been able to tell the difference between ANT and DEC anyway, :-p 3. You said: “…virtual worlds help to redefine what our notion of history actually is. ” I think you’re right…or rather perhaps that it helps us to see what our notion of history might be by peeling back the layers of our understanding. I suspect you’re slipping between using the term history in different ways in what you’ve said (‘historically accurate’, ‘historical relationship’, ‘historical connection’, ‘historical perspective’) We tell stories – create history – whether for just ourselves or for others from what we have as meaningful, yes? – as such virtual worlds stand equally alongside the non-virtual. As I see it, if there is something meaningful (for people – or a person) in a virtual world then history is created, and that meaning is located [if only in a metaphor!] Location is an important part of meaning I think – I suspect to disregard location may be tied up with (what is attributed to) Descartes – that dissociation of mind and body. Maybe this is the nubble of what you’re tussling with (or rather, maybe this is the nubble of what I’M tussling with! :-)). Less to do with avatars, embodiment and presence but more our very embodiment? • Oh interesting point … yes, historically accurate refers to actually something that objectively physically existed, but which we may need to recover our knowledge of, and historical perspective, which is how we as a culture remember the past. And historical relationship which is how we as individuals develop a personal connection with places or events. “Meaning is located” is kind of the point of the entire book, I hope i get that across sufficiently well overall. The thing that gives virtual worlds the sense of being a space is that there is a location that we feel connected to, for some reason, and over time that space can therefore acquire history. Yes of course a website can have a history in the objective meaning of the word; an inception date, a series of revisions, but revisiting that website won’t produce a personal history that gives it meaning and memories. Spaces in virtual worlds do. And what was interesting about the work i was reporting on was that Ian Upton / Pahute was deliberately creating activities that would fast track that layering of a space with personal history. And I’d say that a cultural perspective on history is simply an accumulation of lots of individual ones. And I’d agree totally, well that’s the point of the work I’m doing mainly, which is that meaning only really becomes possible when we’re embodied in virtual worlds. I’m not sure if this is dissociation of mind and body so much as association of mind with extended body. Leave a Reply Fill in your details below or click an icon to log in: WordPress.com Logo You are commenting using your WordPress.com account. Log Out /  Change ) Facebook photo You are commenting using your Facebook account. Log Out /  Change ) Connecting to %s
__label__pos
0.518972
JavaScript Tutorial JS - Introduction JS - Basic JS - Placement JS - Output JS - Statements JS - Syntax JS - Variables JS - Comments JS - Data Types JS - Operators JS - Operator Precedence JS - Condition JS - Switch JS - Functions JS - Objects JS - Loops For JS - Loops While JS - Break JS - Strings JS - String Methods JS - Numbers JS - Number Methods JS - Arrays JS - Array Methods JS - Array Iteration JS - Events JS - Event Listener JS - Event Propagation JS - Date JS - Math JS - Random JS - Boolean JS - Type Conversion JS - RegExp JS - Exception JS - Scope JS - Debugging JS - Hoisting JS - Strict Mode JS - this Keyword JS - Mistakes JS - Best Practices JS - Performance JS - Form Validation JS - ES6 Features JS Objects Object Definitions Object Properties Object Methods Object Constructors Object Prototypes JS Functions Function Definitions Function Parameters Function Call Function Apply Function Closures JS HTML DOM DOM Introduction DOM Methods DOM Selectors DOM HTML DOM CSS DOM Attributes DOM Navigation JS Browser BOM JS - Window JS - Screen JS - Location JS - History JS - Navigator JS - Popup Alert JS - Timing JS - Cookies JS AJAX AJAX - Introduction AJAX - XMLHttp AJAX - Request AJAX - Response AJAX - PHP JS JSON JSON - Introduction JSON - Syntax JSON - Data Types JSON - Parse JSON - Stringify JSON - Objects JSON - Arrays JSON - PHP JSON - JSONP JS References JavaScript Reference JavaScript Methods HTML DOM Reference JavaScript Regular Expressions Regular expressions, commonly known as "regex" or "RegExp", are patterns used to match character combinations in strings. Regular expressions are one of the most powerful tools available today for effective and efficient text processing and manipulations. Regular expressions can be used to perform all types of text search and text replace operations. A regular expression can be a single character, or a more complicated pattern. In JavaScript, regular expressions are also objects. Creating a Regular Expression You construct a regular expression in one of two ways: Using a regular expression literal, which consists of a pattern enclosed between slashes, as follows: Or calling the constructor function of the RegExp object, as follows: Example explained: • parrot is a pattern (to be used in a search) • g is a modifier (performs a global match) Using the constructor function provides runtime compilation of the regular expression. Use the constructor function when you don't know the pattern and are getting it from another source, such as user input. Note: The literal syntax uses forward slashes (/pattern/) to wrap the regular expression pattern, whereas the constructor syntax uses quotes ("pattern"). Using String Methods In JavaScript, regular expressions are often used with the three string methods: search(), replace() and match(). The search() method uses an expression to search for a match, and returns the position of the match. The replace() method returns a modified string where the pattern is replaced. The match() method searches a string for a match against a regular expression, and returns the matches, as an Array object. The search() Method The search() method executes a search for a match between a regular expression and the string. If the match is found it will return the position of the first match, and if the match is not found it will return -1: Run code The following example demonstrates the use of a regular expression with an i flag (ignore case): Run code Regular expressions can make your search much more powerful (case insensitive for example). The replace() Method The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The first parameter will be the value to be found, and the second parameter will be the value to replace it with. Run code By default, the replace() method replaces only the first match. To replace all occurrences, use a regular expression with a g flag (global search): Run code To replace case insensitive, use a regular expression with an i flag (ignore case): Run code The match() Method The match() method searches a string for a match against a regular expression, and returns the matches, as an Array object. Run code Regular Expression Modifiers Modifiers are used to perform global searches, case sensitivity and searching in multiple lines: Modifier Description Example g Performs a global match that is, find all matches rather than stopping after the first match Demo i Perform case-insensitive matching Demo m Perform multiline matching Demo Writing a Regular Expression Pattern Regular expression patterns include the use of letters, digits, punctuation marks, etc., plus a set of special regular expression characters. Brackets are used to find a range of characters: Expression Description Example [abc] Find any character between the brackets Demo [0-9] Find any character between the brackets (any digit) Demo (x|y) Find any of the alternatives specified Demo A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the combination a special meaning: Metacharacter Description Example \d Find a digit Demo \W Find a non-word character Demo \s Find a whitespace character Demo The Quantifiers specifies frequency or position of bracketed character sequences: Quantifier Description Example z+ Matches any string that contains at least one z Demo z* Matches any string that contains zero or more occurrences of z Demo z? Matches any string that contains zero or one occurrences of z Demo Using RegExp Methods In JavaScript, the RegExp object is a regular expression object with predefined properties and methods. The test() method searches a string for a pattern, and returns true or false, depending on the result. The exec() method searches a string for a pattern, and returns the found text as an object. The test() method The test() method executes a search for a match in a specified string. If it finds a match, it returns true; otherwise, it returns false. Use test() whenever you want to know whether a pattern is found in a string. Run code The test() returns a boolean, unlike the exec() which returns a string. The exec() method The exec() method executes a search for a match in a specified string. This method returns the matched text if it finds a match; otherwise, it returns null. Run code Using Regex to verify input Counting number of vowels in a string: Enter some text in the input field to display the number of vowels: VOWELS: Run code Complete RegExp Reference For a complete properties and methods reference, visit our JavaScript RegExp Reference. The reference section contains descriptions and examples of all RegExp properties and methods.
__label__pos
0.550584
Amazing 300 208 dumps secrets Your success in Cisco ccnp security sisas 300 208 official cert guide is our sole target and we develop all our cisco 300 208 braindumps in a way that facilitates the attainment of this target. Not only is our 300 208 sisas study material the best you can find, it is also the most detailed and the most updated. ccnp security sisas 300 208 official cert guide Practice Exams for Cisco CCNP Security ccnp security sisas 300 208 official cert guide are written to the highest standards of technical accuracy. P.S. Realistic 300-208 guidance are available on Google Drive, GET MORE: https://drive.google.com/open?id=1DWWCaNkhxkRc9eJbUhO1wkyzF9H1ehlb New Cisco 300-208 Exam Dumps Collection (Question 14 - Question 23) New Questions 14 Which three pieces of information can be found in an authentication detail report? (Choose three.) A. DHCP vendor ID B. user agent string C. the authorization rule matched by the endpoint D. the EAP method the endpoint is using E. the RADIUS username being used F. failed posture requirement Answer: C,D,E New Questions 15 When using endpoint access control, which two access methods are valid for authentication and authorization? (Choose two.) A. Microsoft Challenge Handshake Authentication B. Protected extensible authentication C. MAC Authentication Bypass D. Password Authentication Protocol Bypass E. Web authentication Answer: C,E New Questions 16 A network engineer is configuring HTTP based CWA on a switch. Which three configuration elements are required? (Choose three.) A. HTTP server enabled B. Radius authentication on the port with MAB C. Redirect access-list D. Redirect-URL E. HTTP secure server enabled F. Radius authentication on the port with 802.1x G. Pre-auth port based access-list Answer: A,B,C New Questions 17 Which two accounting types are used to implement accounting with RADIUS? (Choose two.) A. Network B. User C. Attribute D. Device E. Resource Answer: A,E New Questions 18 What are the four code fields which identify the type of an EAP packet? A. Request, Reply, Accept, Reject B. Request, Reply, Success, Failure C. Request, Response, Success, Failure D. Request, Response. Accept Reject Answer: C New Questions 19 Where is dynamic SGT classification configured? A. Cisco ISE B. NAD C. supplicant D. RADIUS proxy Answer: A New Questions 20 Which default identity source is used by the MyDevices_Portal_Sequence identity source sequence? A. internal users B. guest users C. Active Directory D. internal endpoints E. RADIUS servers Answer: A New Questions 21 Which functionality does the Cisco ISE BYOD flow provide? A. It provides support for native supplicants, allowing users to connect devices directly to the network. B. It provides the My Devices portal, allowing users to add devices to the network. C. It provides support for users to install the Cisco NAC agent on enterprise devices. D. It provides self-registration functionality to allow guest users to access the network. Answer: A New Questions 22 Which two switchport commands enable MAB and allow non-802.1X capable devices to immediately run through the MAB process? (Choose two.) A. authentication order mab dot1x B. authentication order dot1x mab C. no authentication timer D. dot1x timeout tx-period E. authentication open F. mab Answer: A,F New Questions 23 Which two statements about administrative access to the ACS Solution Engine are true? (Choose two.) A. The ACS Solution Engine supports command-line connections through a serial-port connection. B. For GUI access, an administrative GUI user must be created with the add-guiadmin command. C. The ACS Solution Engine supports command-line connections through an Ethernet interface. D. An ACL-based policy must be configured to allow administrative-user access. E. GUI access to the ACS Solution Engine is not supported. Answer: A,B Explanation: who possess the proper administrative credentials. The CLI administrator does not have access to the ACS web GUI. To create an initial GUI administrator account that allows web access to the ACS SE GUI, use the add-guiadmin command to create a GUI account. add-guiadmin : Adds a GUI account that allows access to the SE using the ACS web GUI. 100% Leading Cisco 300-208 Questions & Answers shared by Examcollection, Get HERE: http://www.examcollectionuk.com/300-208-vce-download.html (New 310 Q&As)
__label__pos
0.788773
Geometry Calculating Areas Length and Area Warmup           If each of the side lengths of a triangle triples, then the perimeter will: Is this statement true or false? If the length and width of a rectangle double, then the area will double. If all circular pieces shown are semicircles and quarter circles, what is the area of the yellow region? Bo draws a 1-by-1 square (green). He begins a spiral by adding on a 2-by-1 rectangle (blue), then a 3-by-1 rectangle (pink), etc. Each rectangle is one unit longer than the previous rectangle added. What will be the perimeter of the spiral after the 8th rectangle is added? If the perimeter of Figure #1 is 12, what is the perimeter of the Figure #10? × Problem Loading... Note Loading... Set Loading...
__label__pos
0.999945
top of page • Writer's pictureEddie Black Threat Modeling 101 A shark, swimming in the ocean, the background is dark and ominous. I interviewed with a firm to do Information Security consulting. They had a list of all the regulatory security needs. They then asked what else I thought they needed. I responded with one question. What are you trying to defend? This is the decision that should drive any security mindset. This is the core question found behind threat modeling. Security is focused on risk. The risk equation says the quantified risk is equal to a threat times a vulnerability times impact. It is very similar to the formula that businesses use to calculate expected returns based on a set of investment options. A vulnerability is how adversaries come after you. An example is a thief entering a door someone forgot to lock. Impact is the cost associated with an incident. An example is money lost from lack of sales due to a downed website. A threat is an adversary that causes harm. An example is activists protesting to shut down an organization’s business. Many businesses start with basics. People know computers need antivirus, and they’ve heard of firewalls. But the more security they add, the more expensive it gets. The amount of security spending should be proportionate to the risk faced. And that starts with a question. What are you trying to defend? This is where an organization needs to think like an adversary. How would someone hurt an organization, and how would an organization prevent that? Be creative. Start with the biggest impact. What would cripple the business? The loss of money? How would the money be lost? Armed robbery, business email compromise (scammers), or spending on the wrong resources? The Threat Who can do this? It isn’t necessary to name specific people like the neighbor, Bob. Thieves who want money would commit robbery. Scammers who want to convince an organization to send money for some seemingly legitimate reason would commit digital fraud. The Vulnerability How would they exploit an organization’s status quo? Robbers have an easier time if there’s no armed security. Scammers, pretending to be trusted parties to get an organization to send money, count on people to willingly trust. Think of each of these factors and how someone would prevent that. For example, scammers are easily thwarted by doublechecking with the person who they are impersonating via another method of communication. For example, if the request comes in from the “CEO” over e-mail, call or text the CEO using a known contact number to confirm. A measured, proportionate defense should be tailored to mitigate a vulnerability for a given threat. Safety deposit boxes provide great security for important documents at a reasonable price. They work well for items that they rarely needed, but if someone needs frequent access to something, a safety deposit box becomes an unreasonable solution. People don’t usually put car keys in a safety deposit box. Threat modeling comes down to identifying the things that would hurt the organization to lose, understanding how someone could cause the organization to lose them, and what type of adversary would come for those things with the skill to achieve their aims. Answering these questions will help an organization spend their finite security resources in the most strategic manner possible. 6 views Recent Posts See All bottom of page
__label__pos
0.916318
heatmaps Monitoring quality over time with heap map A particular concern with testing hard disk drives over multiple times is the quality of certain drives may degrade (wear and tear) over time and we failed to detect this degradation. We have certain metrics to gauge any degradation symptom observed for a particular head in a particular drive. For example, with metric A, we are looking at the % change over time reference to the date of the first test o determine whether a head is degraded. Below python code will base on the following table to generate the required heatmap for easy visualization. untitled Calculating %Change import seaborn as sns import numpy as np import pandas as pd import matplotlib.pyplot as plt df1['DATE1'] = df1.DATE.dt.strftime('%m/%d/%Y') df1 = df1.sort_values(by = 'DATE1') # calculate the metric % change and # actual change with reference to each individual head first data df1['METRIC_A_PCT_CHANGE'] = df1.groupby(['SERIAL','HEAD'])['METRIC_A']\ .apply(lambda x: x.div(x.iloc[0]).subtract(1).mul(100)) df1['METRIC_A_CHANGE'] = df1.groupby(['SERIAL','HEAD'])['METRIC_A']\ .apply(lambda x: x - x.iloc[0]) Plotting in HeapMap fig, ax = plt.subplots(figsize=(10,10)) # Pivot it for plotting in heap map ww = df1.pivot_table(index = ['SERIAL','HEAD'], \ columns = 'DATE1', values = "METRIC_A_PCT_CHANGE") g = sns.heatmap(ww, vmin= -5, vmax = 5, center = 0, \ cmap= sns.diverging_palette(220, 20, sep=20, as_cmap=True),\ xticklabels=True, yticklabels=True, \ ax = ax, linecolor = 'white', linewidths = 0.1, annot = True) g.set_title("% METRIC_A changes over multiple Dates", \ fontsize = 16, color = 'blue')   Generated Plots From the heap map, SER_3BZ-0 have some indication of degradation with increasing % Metric A loss over the different test date. untitled Notes • Getting the % percentage change relative to first value of each group. • df.groupby(‘security’)[‘price’].apply(lambda x: x.div(x.iloc[0]).subtract(1).mul(100))   Advertisements
__label__pos
0.88672
maxabsnormalizetransform Normalizes test dataset using values computed on training data by 'maxAbsNormalize' function. Attention: Available only with Activate commercial edition. Syntax X_normalized = maxabsnormalizetransform(parameters,X) Inputs X Input data to be normalized. Type: double Dimension: vector | matrix parameters Struct containing max absolute of each column of training data. It is the output of 'maxAbsNormalize' function. Type: double | integer Dimension: struct Outputs X_normalized Normalized input records. Type: integer Dimension: vector | matrix Example Usage of maxabsnormalizetransform X = [1, -1, 2; 2, 0, 0; 0, 1, -1]; X_test = [-3 -1 4]; [X_scaled, parameters] = maxabsnormalize(X); X_test_scaled = maxabsnormalizetransform(parameters, X_test); > X_test_scaled X_test_scaled = [Matrix] 1 x 3 -1.50000 -1.00000 2.00000
__label__pos
0.526851
Create Hybrid Test Automation Framework – Interface Contracts Datetime:2016-08-23 01:15:49          Topic: Automated Testing           Share Guys, I am so excited to announce the creation of new series of blog posts- Design & Architecture . The main idea behind this is that I will show more abstract, visionary improvements that you might bring to your test automation projects that do not depend on the used test automation framework such as WebDriver or Testing Frame work . The first articles from Design & Architecture Series are going to be dedicated to the creation of a  Hybrid Test Automation Framework . Through this type of test automation framework, you can quickly execute your tests through different test automation frameworks without changing a single line of code, using only configuration switches. As you may guess, the creation of a Hybrid Test Automation Framework is not an easy job. A lot of code should be written so I cannot explain everything in a single post. Because of that, I am going to separate logically in the best possible way the content. In this first article, I am going to explain to you how to create the core interface contracts that your test pages and tests will use so that they do not depend on a concrete implementation and at the same time follow the best practices and SOLID principles . Quick Navigation Hybrid Test Automation Framework- Interfaces Primary IDriver Interface IElementFinder Interface IJavaScriptInvoker Interface INavigationService Interface IDialogService Interface Hybrid Test Automation Framework in Tests Hybrid Test Automation Framework Base Page Non-Hybrid Page Object Hybrid Test Automation Framework Test Example Non-Hybrid Test Automation Framework Test Example Hybrid Test Automation Framework- Interfaces Primary IDriver Interface This is the main interface that you will use in your code. As you can found out from the lines below it does not contain any methods, it only inherits a couple of other important contacts. The main idea behind this is to follow the Interface Segregation SOLID Principle . If you need to find elements, you will use the IElementFinder interface if you require updating cookies you will use the I Cookie Service and so forth. The principle states that no client should be forced to depend on methods that it does not use so we split the big interface in several smaller logically separated parts. public interface IDriver : IElementFinder , INavigationService , ICookieService , IDialogService , IJavaScriptInvoker , IBrowser { } view raw IDriver.cs hosted by GitHub IElementFinder Interface public interface IElementFinder { TElement Find<TElement>(By by) where TElement : class , IElement; IEnumerable<TElement> FindAll<TElement>(By by) where TElement : class , IElement; bool IsElementPresent ( Core.By by ); } view raw IElementFinder.cs hosted by GitHub The IElementFinder contract holds methods for locating elements on the pages. Also, it contains a logic for checking if an element is present. The methods return IElement interface which represents a base HTML page element. public interface IElement : IElementFinder { string GetAttribute ( string name ); void WaitForExists (); void WaitForNotExists (); void Click (); void MouseClick (); bool IsVisible { get ; } int Width { get ; } string CssClass { get ; } string Content { get ; } } view raw IElement.cs hosted by GitHub To support searching of elements inside other container items such as DIVs, IElement inherits from the  IElementFinder interface. All different controls will inherit from the IElement contract. You will find more information about this in the next articles from the series. Similar to the WebDriver implementation we have an abstract static class By for setting the elements' localization strategy. public class By { public By ( SearchType type , string value ) : this (type, value, null ) { } public SearchType Type { get ; private set ; } public string Value { get ; private set ; } public static By Id ( string id ) { return new By(SearchType.Id, id); } public static By InnerTextContains ( string innerText ) { return new By(SearchType.InnerTextContains, innerText); } public static By Xpath ( string xpath ) { return new By(SearchType.XPath, xpath); } public static By Id ( string id , IElement parentElement ) { return new By(SearchType.Id, id, parentElement); } public static By CssClass ( string cssClass ) { return new By(SearchType.CssClass, cssClass); } public static By Name ( string name ) { return new By(SearchType.Name, name); } } view raw By.cs hosted by GitHub IJavaScriptInvoker Interface It holds a logic for JavaScript execution. public interface IJavaScriptInvoker { string InvokeScript ( string script ); } view raw IJavaScriptInvoker.cs hosted by GitHub INavigationService Interface INavigationService interface has several methods regarding navigation such as navigating by a relative URL or absolute URL . Also, it contains logic for waiting for specific UR L . public interface INavigationService { event EventHandler<PageEventArgs> Navigated; string Url { get ; } string Title { get ; } void Navigate ( string relativeUrl , string currentLocation , bool sslEnabled = false ); void NavigateByAbsoluteUrl ( string absoluteUrl , bool useDecodedUrl = true ); void Navigate ( string currentLocation , bool sslEnabled = false ); void WaitForUrl ( string url ); void WaitForPartialUrl ( string url ); } view raw INavigationService.cs hosted by GitHub IDialogService Interface Through it, you can handle different dialogs. public interface IDialogService { void Handle ( System.Action action = null , DialogButton dialogButton = DialogButton.OK); void HandleLogonDialog ( string userName , string password ); void Upload ( string filePath ); } view raw IDialogService.cs hosted by GitHub IBrowser Interface This is one of the most important interfaces, part of the main IDriver interface. Through the  IBrowser contract, you can execute browser-specific actions such as switching frames, refreshing, clicking back/forward buttons and so on. public interface IBrowser { BrowserSettings BrowserSettings { get ; } string SourceString { get ; } void SwitchToFrame ( IFrame newContainer ); IFrame GetFrameByName ( string frameName ); void SwitchToDefault (); void Quit (); void WaitForAjax (); void WaitUntilReady (); void FullWaitUntilReady (); void RefreshDomTree (); void ClickBackButton (); void ClickForwardButton (); void LaunchNewBrowser (); void MaximizeBrowserWindow (); void ClickRefresh (); } view raw IBrowser.cs hosted by GitHub Hybrid Test Automation Framework in Tests This is how will look like the base page for all pages of your hybrid test automation framework. Hybrid Test Automation Framework Base Page public abstract class BasePage { private readonly IElementFinder elementFinder; private readonly INavigationService navigationService; public BasePage ( IElementFinder elementFinder , INavigationService navigationService ) { this .elementFinder = elementFinder; this .navigationService = navigationService; } protected IElementFinder ElementFinder { get { return this .elementFinder; } } protected INavigationService NavigationService { get { return this .navigationService; } } } view raw BasePage.cs hosted by GitHub As you can see the base page does not require all interfaces of the IDriver contract. Most pages need only a way to find elements and to navigate. Non-Hybrid Base Page To see the difference, you can find below the code of the non-hybrid version of the BasePage class . public abstract class BasePage { protected IWebDriver driver; public BasePage ( IWebDriver driver ) { this .driver = driver; } public abstract string Url { get ; } public virtual void Open ( string part = " " ) { this .driver.Navigate().GoToUrl( string .Concat( this .Url, part)); } } view raw BasePage.cs hosted by GitHub As you can see, we pass the whole IWebDriver interface. However, often we do not need all methods that it exposes. Hybrid Page Object public partial class BingMainPage : BasePage { public BingMainPage ( IElementFinder elementFinder , INavigationService navigationService ) : base (elementFinder, navigationService) { } public void Navigate () { this .NavigationService.NavigateByAbsoluteUrl( @"http://www.bing.com/" ); } public void Search ( string textToType ) { // It is going to be implemented in the next article. ////this.SearchBox.Clear(); ////this.SearchBox.SendKeys(textToType); this .GoButton.Click(); } public int GetResultsCount () { int resultsCount = default ( int ); resultsCount = int .Parse( this .ResultsCountDiv.Content); return resultsCount; } view raw BingMainPage.cs hosted by GitHub Similar to the base page, here we pass only the abstract hybrid test automation framework's contracts. Also, we need to implement the Navigate method manually. Non-Hybrid Page Object public partial class BingMainPage : BasePage { public BingMainPage ( IWebDriver driver ) : base (driver) { } public override string Url { get { return @"http://www.bing.com/" ; } } public void Search ( string textToType ) { this .SearchBox.Clear(); this .SearchBox.SendKeys(textToType); this .GoButton.Click(); } public int GetResultsCount () { int resultsCount = default ( int ); resultsCount = int .Parse( this .ResultsCountDiv.Text); return resultsCount; } } view raw BingMainPage.cs hosted by GitHub The only difference compared to the hybrid version is that the BingMainPage is coupled with the concrete IWebDriver implementation. Hybrid Page Map public partial class BingMainPage { public IElement SearchBox { get { return this .ElementFinder.Find<IElement>(By.Id( " sb_form_q " )); } } public IElement GoButton { get { return this .ElementFinder.Find<IElement>(By.Id( " sb_form_go " )); } } public IElement ResultsCountDiv { get { return this .ElementFinder.Find<IElement>(By.Id( " b_tween " )); } } } view raw BingMainPage.cs hosted by GitHub Here I used the improved version of the Page Object Pattern - the element map is implemented as a partial class of the primary page object class. We use the ElementFinder property that comes from the BasePage class to locate the different elements. As you have probably noticed, the different properties return the I El ement interface so that the map is not coupled with the concrete implementation of the controls. Non-Hybrid Page Map public partial class BingMainPage : BasePage { public IWebElement SearchBox { get { return this .driver.FindElement(By.Id( " sb_form_q " )); } } public IWebElement GoButton { get { return this .driver.FindElement(By.Id( " sb_form_go " )); } } public IWebElement ResultsCountDiv { get { return this .driver.FindElement(By.Id( " b_tween " )); } } } view raw BingMainPage.cs hosted by GitHub Similar to the page object class the non-hybrid element map is coupled with the WebDriver's concrete implementation. Hybrid Test Automation Framework Test Example [TestClass] public class BingTests { private BingMainPage bingMainPage; private IDriver driver; [TestInitialize] public void SetupTest () { this .driver = new SeleniumDriver(); this .bingMainPage = new BingMainPage( this .driver, this .driver); } [TestCleanup] public void TeardownTest () { this .driver.Quit(); } [TestMethod] public void SearchForAutomateThePlanet () { this .bingMainPage.Navigate(); this .bingMainPage.Search( " Automate The Planet " ); this .bingMainPage.AssertResultsCountIsAsExpected( 264 ); } } view raw BingTests.cs hosted by GitHub As you can see from both examples, the code is almost identical with the only difference that our test automation framework can be switched in the first version if you assign another concrete implementation to the IDriver interface variable. Non-Hybrid Test Automation Framework Test Example [TestClass] public class BingTests { private BingMainPage bingMainPage; private IWebDriver driver; [TestInitialize] public void SetupTest () { this .driver = new FirefoxDriver(); this .bingMainPage = new BingMainPage( this .driver); } [TestCleanup] public void TeardownTest () { this .driver.Quit(); } [TestMethod] public void SearchForAutomateThePlanet () { this .bingMainPage.Open(); this .bingMainPage.Search( " Automate The Planet " ); this .bingMainPage.AssertResultsCountIsAsExpected( 264 ); } } view raw BingTests.cs hosted by GitHub About List
__label__pos
0.990768
Expand my Community achievements bar. SOLVED Where to find older copies of the legacy javascript libraries? Avatar Level 2 I am attempting to reverse engineer some tracking anomalies which appear to include edited versions of the H.x.x.x tracking library; but I can only get the original for the latest release.  Is there an archive somewhere of the previous tracking libraries? Specifically I am looking for * SiteCatalyst code version: H.27.4. * but I may need other versions of this in the future for this project.   Thank you, Geoff 1 Accepted Solution Avatar Correct answer by Level 10 Geoff, We only provide the most current versions of AppMeasurement and s_code in the Analytics code library. You may be able to retrieve some older versions of the code within DTM. In DTM, you can select which code version to deploy, then you can select custom and it should open the code library in a text editor Regards, Jantzen  View solution in original post 2 Replies Avatar Correct answer by Level 10 Geoff, We only provide the most current versions of AppMeasurement and s_code in the Analytics code library. You may be able to retrieve some older versions of the code within DTM. In DTM, you can select which code version to deploy, then you can select custom and it should open the code library in a text editor Regards, Jantzen  Avatar Level 10 Geoff, Did you have additional questions here? If not, would you be ok with marking my previous answer correct?   Cheers, Jantzen
__label__pos
0.931726
Windows has a strange habit of corrupting your profile at times. This can happen for a number of reasons. In my experience it is usually from unexpected shut downs or if Windows blues screens. I have never seen it happen when I intentionally restart my computer and then my profile is missing. Scenario Here is what happened to me today. I restart my work computer about once a week because corporate puts all of these lovely programs on it that kill its performance. Not restarting isn’t really an option when you find that you are typing faster than your computer can keep up showing it on your screen. So to fix the constant freezing and just general sluggishness, I just give up, close everything and restart my PC. Maybe even install Visual Studio updates or whatever so I take advantage of the opportunity. Obscure problem 1. I restart the computer 2. Computer boots back up 3. I log back into Windows only to be met with a message that said something like “Your profile couldn’t be loaded, this is often fixed by logging out and logging back in.” 1. I didn’t take a screenshot, I just wanted to get back to work. 4. Well as usual following the advice did nothing, I logged out and back in, my profile seemed to have been wiped out. 5. I restart my computer again and hope it would come back. Profile is still gone. 6. I review my profiles and see that my profile is in “Backup status” (21 GB size) and I am currently using a new temporary profile in “Temporary status” (7 MB size). 7. I saw a somewhat harmless fix which I have a link to in the next section: 1. Restart your computer in safe mode 2. Then restart your computer regular 3. Your profile should load Fix? No guarantees I cannot guarantee this will work for everyone. This is a very strange problem that has presented itself to me in various forms over the years. It keeps morphing. Bit Locker If your computer has bit locker on it, proceed with caution. It is possible for you to get locked out of your machine and require the bit locker key if you follow these instructions. Credit where credit is due I used the top of this post as guidance. I will admit I didn’t read the whole thing as I was still troubleshooting. The above link is what I used as guidance. As previously mentioned here are the recommended steps: 1. Restart your computer in safe mode 2. Then restart your computer regular 3. Your profile should load However as I have indicated if you are using Bit Locker proceed with caution as this is what I had happen to me and I will admit my heart dropped into my feet for a moment: 1. Restart your computer in safe mode. This has instructions with pictures. 1. Click on Windows icon in the lower left to raise the start menu 2. Click on Power menu item in start menu 3. While holding shift click on Restart 4. Click on Troubleshoot 5. Click on Advanced options 6. Click on Start-up Settings 7. Click restart 2. You will be challenged to enter your Bit Locker key 3. Ignore this and press the Escape key 4. It will challenge you again on a different screen 5. Perform a hard restart on your machine by holding down the power button 6. Start your computer by pressing the power button 7. Hopefully Bit Locker does not challenge you 1. If you are told you do not have a boot drive, this is because Bit Locker has been engaged. 2. You will need your Bit Locker key to undo this which is why I was cautioning. I hope you have your key. 8. Windows should start to load, login as normal 9. Hopefully your profile loads Why now? This problem presented itself to me now even though the KB named in the article above was written in February because my company is slow to adopt new Windows updates. They are very strict with security so I am slow to get any new features or fixes for that matter. However the symptoms caused by KB4532693 are exactly what I was experiencing. I hope it doesn’t happen again because this was a miserable two hours I lost of trying to carefully decide how to hang myself. Luckily escaped without any problems, but I cannot say things will always end so well. This is just one more reason why I never shut off my work computer.
__label__pos
0.818037
Please do have a look at ActiveRecord::Validations::ClassMethods for a higher level of validations. Active Records implement validation by overwriting Base#validate (or the variations, validate_on_createand validate_on_update). Each of these methods can inspect the state of the object, which usually means ensuring that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression). Example: class Person < ActiveRecord::Base protected def validate errors.add_on_empty %w( first_name last_name ) errors.add("phone_number", "has invalid format") unless phone_number =~ /[0-9]*/ end def validate_on_create # is only run the first time a new object is saved unless valid_discount?(membership_discount) errors.add("membership_discount", "has expired") end end def validate_on_update errors.add_to_base("No changes have occurred") if unchanged_attributes? end end person = Person.new("first_name" => "David", "phone_number" => "what?") person.save # => false (and doesn't do the save) person.errors.empty? # => false person.errors.count # => 2 person.errors.on "last_name" # => "can't be empty" person.errors.on "phone_number" # => "has invalid format" person.errors.each_full { |msg| puts msg } # => "Last name can't be empty\n" + # "Phone number has invalid format" person.attributes = { "last_name" => "Heinemeier", "phone_number" => "555-555" } person.save # => true (and person is now saved in the database) An Errors object is automatically created for every Active Record. Namespace Methods E I S V Constants VALIDATIONS = %w( validate validate_on_create validate_on_update )   Instance Public methods errors() Returns the Errors object that holds all information about attribute error messages. # File activerecord/lib/active_record/validations.rb, line 1129 def errors @errors ||= Errors.new(self) end invalid?() Performs the opposite of valid?. Returns true if errors were added, false otherwise. # File activerecord/lib/active_record/validations.rb, line 1124 def invalid? !valid? end save_with_validation(perform_validation = true) The validation process on save can be skipped by passing false. The regular ActiveRecord::Base#save method is replaced with this when the validations module is mixed in, which it is by default. # File activerecord/lib/active_record/validations.rb, line 1087 def save_with_validation(perform_validation = true) if perform_validation && valid? || !perform_validation save_without_validation else false end end save_with_validation!() Attempts to save the record just like ActiveRecord::Base#save but will raise a RecordInvalid exception instead of returning false if the record is not valid. # File activerecord/lib/active_record/validations.rb, line 1097 def save_with_validation! if valid? save_without_validation! else raise RecordInvalid.new(self) end end valid?() Runs validateand validate_on_createor validate_on_updateand returns true if no errors were added otherwise false. # File activerecord/lib/active_record/validations.rb, line 1106 def valid? errors.clear run_callbacks(:validate) validate if new_record? run_callbacks(:validate_on_create) validate_on_create else run_callbacks(:validate_on_update) validate_on_update end errors.empty? end Instance Protected methods validate() Overwrite this method for validation checks on all saves and use Errors.add(field, msg)for invalid attributes. # File activerecord/lib/active_record/validations.rb, line 1135 def validate end validate_on_create() Overwrite this method for validation checks used only on creation. # File activerecord/lib/active_record/validations.rb, line 1139 def validate_on_create end validate_on_update() Overwrite this method for validation checks used only on updates. # File activerecord/lib/active_record/validations.rb, line 1143 def validate_on_update end
__label__pos
0.622119
Home » SQL & PL/SQL » SQL & PL/SQL » Improve running time Improve running time [message #425821] Mon, 12 October 2009 07:02 Go to next message eyalle Messages: 5 Registered: October 2009 Junior Member Hi, i would like to improve the running time for the following code: SELECT distinct r.rule_id, b.be_id, b.be_name FROM rules r, rule_param_be_type pbt, rule_param_fe_type pft, be b, be_types bt, fe f WHERE r.RULE_ID = pbt.rule_id(+) and r.RULE_ID = pft.rule_id(+) and pbt.be_type_id = b.be_type_id and pft.fe_type_id = f.fe_type_id and b.be_type_id = bt.be_type_id and b.fe_id = f.fe_id and r.RULE_ID = r.rule_id and pbt.param_id = 0 and pft.param_id = 0 does anyone has any idea on how to do it so running time will improve ? thank's Re: Improve running time [message #425831 is a reply to message #425821] Mon, 12 October 2009 07:29 Go to previous messageGo to next message Kevin Meade Messages: 2101 Registered: December 1999 Location: Connecticut USA Senior Member Here are some comments: 1) learn how to format your code when you post here. First use a code formatter to format your sql (TOAD, or this are two possibilities). Second use the {..} to wrap CODE tags around your code after you paste it into your post. That way your formatting does not get lost when the page is rendered. 2) Check you outerjoins. Seems to me your are missing some. For your sql, if AND r.rule_id = pft.rule_id (+) finds no row in pft, then what happens at this line AND pft.fe_type_id = f.fe_type_id? As it stands your existing outer joins are useless and you can remove them altogether. Why did you think you needed them anyway? SELECT DISTINCT r.rule_id, b.be_id, b.be_name FROM rules r, rule_param_be_type pbt, rule_param_fe_type pft, be b, be_types bt, fe f WHERE r.rule_id = pbt.rule_id (+) AND r.rule_id = pft.rule_id (+) AND pbt.be_type_id = b.be_type_id AND pft.fe_type_id = f.fe_type_id AND b.be_type_id = bt.be_type_id AND b.fe_id = f.fe_id AND r.rule_id = r.rule_id AND pbt.param_id = 0 AND pft.param_id = 0 3) I have serious doubts about the validity of your sql. Have you actually checked it at all. Tell me, what does this do? AND r.rule_id = r.rule_id 4) Your tuning question is wide open. We don't know much about your data or database so there could be lots of answers. However I might suggest this: you should create indexes to support your joins. When doing this consider adding extra columns to your indexes as referenced by your sql so that you can skip table accesses. I might conside the following indexes: rules (rule_id) rule_param_be_type (param_id,rule_id,be_type_id) rule_param_fe_type (param_id,rule_id,fe_type_id) be (be_type_id,fe_id,name) fe (fe_type_id) bt (be_type_id) Of particular note is: be (be_type_id,fe_id,name) Notice name is on the end of the index. It appears in the select list but not in the where clause. Oracle can skip going to the BE table assuming no other columns are required that are not in used indexes in the query. This avoids extra I/O. Good luck, Kevin Re: Improve running time [message #425850 is a reply to message #425831] Mon, 12 October 2009 08:39 Go to previous messageGo to next message eyalle Messages: 5 Registered: October 2009 Junior Member Thank's Kevin of much help.. Smile Re: Improve running time [message #425857 is a reply to message #425821] Mon, 12 October 2009 10:33 Go to previous message Kevin Meade Messages: 2101 Registered: December 1999 Location: Connecticut USA Senior Member no sweat Just make sure you RESEARCH these features is you intend to use them. RESEARCH means you go out to the web and do some reading, then you log into a test database and you do some testing, then you formulate a plan and test it out. Never use a feature unless you understand it and have experimented with it on your own. Good luck, Kevin Previous Topic: converting unknown amount of rows to columns Next Topic: This returns "table does not exist" but reads correctly in my DBMS_OUTPUT. HELP! thx... Goto Forum:    Current Time: Sat Apr 29 18:37:38 CDT 2017 Total time taken to generate the page: 0.07745 seconds
__label__pos
0.568394
How to Uninstall Bitdefender From Mac or PC Remove this antivirus software from any computer Although Bitdefender is a great antivirus solution, if you want to change to another, or switch to a free solution, you need to know how to uninstall Bitdefender. Some have run into problems doing so due to the way Bitdefender software is structured and how it can have multiple applications per subscription, but just follow these steps and you'll uninstall Bitdefender in no time. These instructions apply to computers running Windows 7, 8.1, and 10, as well as recent versions of macOS. How to Uninstall Bitdefender on Windows Windows has a robust uninstall system and remains the best way to uninstall Bitdefender, whatever version you're running.  It's incredibly important to have some form of antivirus on your system, whatever operating system you're running. Once you've uninstalled Bitdefender, it's recommended you install something else, even if it's just the free version. 1. Search for Programs in the Windows search bar, then select Add or Remove Programs in Windows 10, or select Programs and Features if you're on Windows 7 or 8.1. 2. Use the list or search bar to find and select Bitdefender Antivirus, then select Uninstall > Uninstall. If asked for administrator approval, give it. Selecting Bitdefender 3. Bitdefender may ask if you want to go ahead with the uninstall process. Select Yes to confirm that you do. Uninstall Bitdefender The uninstall process can take a short while depending on your system's specifications. You can wait it out, answer Bitdefender's survey to let the developers know why you're uninstalling the software, or do something else. 4. When the uninstall process is finished, select Finish. How to Uninstall Bitdefender Agent From Windows If you're happy enough with simply removing the main antivirus program, then you can stop your uninstall process there. However, if you want to remove any trace of Bitdefender from your system, then it's a good idea to follow these steps to remove the Bitdefender Agent, too. Do this if you're planning to install another antivirus program to replace Bitdefender. 1. Search for Programs in the Windows search bar, then select Add or Remove Programs in Windows 10, or select Programs and Features if you're on Windows 7 or 8.1. 2. Search for Bitdefender again, select Bitdefender Agent from the list, then select Uninstall > Uninstall. Bitdefender Uninstall 3. Wait for the uninstall process to complete. After a few minutes your Windows PC should be entirely free of Bitdefender Antivirus. How to Uninstall Bitdefender on macOS Uninstalling Bitdefender on macOS is no more complicated than on Windows, but it does take a few different steps to complete. Follow these instructions to remove Bitdefender antivirus from your Mac for good. 1. Open Finder, then select Go > Utilities. Alternatively, press CMD+U. Go > Utilities 2. Double-click or tap BitdefenderUninstaller to start the uninstallation process. 3. When the pop-up menu appears asking you to confirm your selection, click Uninstall. 4. If asked, enter your administrator password. 5. Wait for the uninstall to complete. How to Completely Remove Bitdefender on macOS Although you can technically now consider the removal of Bitdefender Antivirus complete, there are some elements left behind that the uninstaller doesn't remove. If you want to get rid of everything Bitefender originally installed, follow these steps. 1. Open Macintosh HD > Library and look for the Bitdefender folder.  2. Click and drag the folder to Trash, or right-click the folder and click Move to Trash. Give administrator password approval if prompted. 3. The Bitdefender icon might remain in the Dock. If it does, right-click (or tap and hold) and click Options > Remove from Dock. 4. Navigate to Macintosh HD > Library > Application Support and look for the Antivirus for Mac folder. This is where quarantined elements are kept. If you want to remove those, too, click-drag the whole folder to Trash. There are some application cleaner apps out there that can remove software like Bitdefender antivirus. While they aren't strictly necessary, they can speed up the process.   Can't Uninstall Bitdefender? Use the Bitdefender Uninstall Tool Some users have run into issues uninstalling Bitdefender using the above methods. Sometimes, they find the uninstall process is interrupted, or there's no listing for Bitdefender or Bitdefender Agent on their system, even while the application remains working. If that sounds like you, then your best bet is to use a Bitdefender Uninstall tool. Here's how to do it. 1. Visit the Bitdefender Uninstall Tool webpage and select the product you're trying to uninstall. Bitdefender uninstall page 2. Look for the Bitdefender product you wish to uninstall, then select its green Uninstall tool. When prompted, select Directly download the uninstaller. Uninstall tools 3. A black window will appear telling you it wants to uninstall Bitdefender. Select Uninstall. Uninstall tool 4. You're then shown a loading bar while the uninstall process completes. When it's finished, select Restart to reboot your system and finalize the process. Was this page helpful?
__label__pos
0.542589
Blog Blog This screenshot says it all: the first line, the header, shows the installed iOS version: So iTunes would like me to update from 10.1.1 to 10.1.1... hmm. I had a server with a complex network configuration: 2 network interface cards, with various VLAN configurations. When upgrading, i decided to use Migration Assitant only for the Network Settings. It's nice, so i deselected everything but the Network Settings. It took 16 minutes and a reboot. When the server came back up, guess what? Network Settings were not imported at all! I think it actually imported some other settings, but no Network Settings. Boo. Se una persona non sa cosa significa CAD e cerca su internet, troverà referenze praticamente solo per Computer Aided Design. Mentre se uno volesse sapere il significato di CAD nella sicurezza software italiana, troverà ben poco. Ed i siti che contengono quell'acronimo, non ne contengono il significato o la definizione. Semplicemente danno per scontato che si sappia cosa abbrevi. Il sito ufficiale del Codice Amministrazione Digitale (CAD): http://archivio.digitpa.gov.it/amministrazione-digitale/CAD-testo-vigente il sito specifica all'inizio: Si pecisa che il testo normativo qui di seguito esposto (così come quello di qualsiasi altra disposizione normativa pubblicata sul sito dell'Agenzia)  non ha alcun carattere di ufficialità. Il che mi fa pensare: se si tratta di "testo normativo" non ufficiale, allora non dovrebbe essere un "testo informativo"? Quale è il senso di una normativa non ufficiale? Wait But Hi survey. Check this out! https://wbw.typeform.com/to/NqEp2V I just completed the survey for the event. I'm pretty excited. Sounds like it could go really bad, or really good! I recently heard an interview where Elon Musk was asked about simulation theory, which sparked some more reading and thinking, until i viewed the topic from this angle presented here, so i decided to write a blog post.In other words, if we had computers so powerful, that they were able to simulate our reality 100%, so simulate life, and consciousness as well, do you think we would actually use them to run experiments about ourselves, maybe to predict what will happen with us, or where we originated from? Kind of like: "Hey, let's write a real life simulator, feed it some human consciousness data, and see what happens. Do you think the simulated beings will act like us? And how will they act in the future?" You know, kind of what we do now with the weather: we collect lots of data from the environment/weather, then we write models that can fit that data, then we run simulations, and see what would happen if the initial conditions are x and y. And what would happen in a million years. And what would happen tomorrow, given that today is like this. So, since we do this for the weather, (and many other things) why would we not do it for human beings and consciousness? And if this is the case, then most likely this very reality we live in is actually a simulation. Because at this rate of technological advance, it will not take much (at an evolutionary scale) to reach a point in which we will have these resources, these computers that could be able to run such simulations. I mean at the current rate, it probably shouldn't take more than a few decades. But even if it took 1000 times more than that, then say 10, 20, 30 thousand years. That's still not much considering the millions of years we have been around, right? But did Elon really say we are most likely part of a simulation? Elon Musk was asked to talk about simulation theory at an interview in June at Recode's National Conference. Here are two articles about that. So the above article feed on an interview that Musk gave early June 2016, and insist that Musk's point of view is that it is almost certain that we live in a simulation. However, the way i see it, that is not quite what Musk said. What Musk did say, is that if his argument is true, than we probably are living in a simulation. Here's what he did: 1. First he makes an argument. But he doesn't state he believes that argument. Quite the contrary, he actually asks for it to be challenged: "Tell me what's wrong with that argument. Is there a flaw in that argument?" 2. The interviewer, however, doesn't challenge the argument. And states there is no flaw with it. 3. Then he reaches the conclusion that, if there is no flaw in the argument (which he never stated there wasn't any flaw in it), then there is 1 in billions chance that we live in base reality. Basically what he stated is that if you believe in that argument, then most likely we live in base reality. He didn't directly say he believes most likely we live in base reality. Indeed, there are other outcomes (which have been widely discussed, here's a collection of some) he didn't discuss, for example: 1. we, as humans, might never reach the point in which we can simulate consciousness. 2. we might be extinct before we can reach that point; 3. we can simply not be interested in running simulations, because we might somehow understand how consciousness can be linked to suffering, and therefore why create more suffering by creating more (even if just simulated) individuals? 4. ...   Some of my thoughts Certainly, one thing i can say. Looking back in time and what we believed in (being at the center of the universe, that eyes emitted beams that allowed us to see, etc) and what we believe in now, it certainly seems like the rate of understanding things increases, and it feels like we are able to model more and more of our perceived reality. Therefore, it feels just logical to infer that at this rate, there should be no reason why we should not be able to simulate consciousness as well. No logical reason, at least. Religious and tradition and fear based reasons, plenty. Logical though? How logical did it feel to believe that the earth was flat, and just not being able to explain what happened at the end of earth? Maybe just as logical as it is to believe that humans have this spearate thing called consciousness, that we will never be able to reproduce. However, whether we live in a simulation or not, makes absolutely no difference to us... or shouldn't at least. Because simulation or not, we have but the rules of this game to play with. And it feels like there is really just one universal instruction code set universally programmed in all living beings: reduce suffering as much as possible. So if we want to live a life with the least amount of suffering, it makes little difference whether we are part of a simulation or not, unless we could be capable of popping out of it. Dwelling in these thoughts, therefore, feel to me like investing energy and time into something that doesn't ultimately help me reduce my suffering any more than watching a movie. Quantum uncertainty and simulation theory So basically we do not know the exact location and momentum of an electron, according the Heisenberg uncertainty principle, until we are actually able to measure it. Or the double slit experiment, where, until we don't actually measure which slit an electron goes through, it behaves as if it goes through both. But when we observe, the wave function collapses and it behaves like a single particle. But if we were in a simulation, then there certainly would be no need to simulate everything down to the tiniest particle. As long as the humans in the experiment can't infer something "strange" is going on, then the simulation experiment would not be ruined. So one detail of the simulation theory would be, that details are simulated only when required. Kind of like what we do now with our awesome video games: the graphics, the shadows, the details, the resolution and the physics is rendered only where player is looking. There is no need to waste computing power to simulate everything in the entire video game reality at one time. There just has to be enough to ensure consistency. So in the unseen world, it's good enough that say an object stays there where the player put it, unless some other player comes and moves it. Could this also explain the mysterious consciousness that the electron in the double slit experiment suddenly gains when it "knows" it's observed, and now turns from a wave of probable positions into a single 4 dimensional coordinate? I've always been a fan of Carla Bley and her Escalator Over the Hill. Love that kind of work. But i never heard her work with Swallow, duets and the trios. Loved the simple simple song. Ingenious. Did anyone else get this email by Google? OK. So i had to read it like 3 times and i still didn't understand it. So i use Google calendars regularly, and i don't understand this email. It would take me like 20-30 mins of research to figure out exactly what this all means and how it would affect me. • How does it work now, before the change? • What are the domain's external sharing options? • What changes will take effect immediately? • What are primary and secondary calendars? This is the gist of the email, stripping down all the rest, which discusses the changes: The Google team will change the behavior of calendars to follow external sharing setting. Change from what? To what? What has changed? The reader doesn't care much about the new state today, because the reader doesn't know or remember most of times what the old state was. But almost everyone will have an opinion, if they read something for example, like "Google Calendar team has changed how usernames are displayed: Before the change, no real names were displayed. After the change, on June 23 2023, real names will be displayed with usernames." No we can go into detail, thank you. I think people who write publicly, could be more aware, when covering something technical, to start out really simple, so everyone can understand. Then, go into more details. This way everyone can understand and decide immediately if this is something that interests them or not. In this particular case, there are changes in the Google Calendar which has to do with sharing or visibility or privacy. That's it.   Subject: Important change in behavior of Google Calendar events with public visibility We will send a copy of this message in your account's primary language as soon as the translations are available. We anticipate this process to take 1-2 weeks. Hello Administrators, On May 16, 2016, the Google Calendar team will change the behavior of calendar events that users have intentionally marked as public to strictly follow a domain’s external sharing options setting for both primary and secondary calendars, set from the Admin console. This change gives domain administrators more control over how users are sharing their calendar events with people outside of the domain. Note: If your domain external sharing setting is set to Share all information, then there's no behavior change. The change will take effect immediately on the web. Calendars and events synced on mobile may remain visible until the device re-syncs. All events created after May 16, 2016, will appear as free/busy on all platforms. If users want to share calendar events with external users, but keep their primary work calendars private or free/busy, they can still create separate secondary calendars for that purpose. We recommend the following actions: • If you want to continue sharing calendar events with external users but keep primary calendars private, set the access for primary calendars to Only free/busy information, while setting the access for secondary calendars to Share all information. Then, encourage your users to create public events on secondary calendars. • Confirm your current Google Calendar External sharing options in the Admin console (Apps > Google Apps > Calendar > Sharing settings). Learn more about how to Set calendar sharing options. If you have additional questions or need assistance, contact Google Apps Support. Sincerely, The Google Apps Team I am upgrading from an iPad Mini 2 retina Cellular to an iPad Mini 4 Cellular. Should be pretty straight forward right? This was my strategy: 1. Backup up iPad Mini 2 with iTunes via USB; 2. Turn iPad Mini 4 on, setup as new iPad and upgrade to latest iOS. 3. Restore iPad Mini 2 backup on to iPad Mini 4. I have been using a Mac for about 12 years now, and have just recently decided to start with a completely fresh account, instead of upgrading all the time, to clean up all the leftover stuff from very old apps and OSs i no longer need. So keep this in mind too. This is what actually happened: • Backup went fine. It was very fast. • After setting up iPad mini 4, i had to iOS upgrade, but it kept failing. It only worked after a reboot. So i had to reboot a first-time-booted iPad Mini 4 to make the iOS upgrade work (from 9.0 to 9.2.1)!! • Restore started OK. Then iTunes started to give me useless warnings and alerts that it was not able to connect to the iPad, while it connect the iPad just fine. • Then iTunes started telling me that the new iPad, which i have just finished updating, needed to be updated. It said, the current software installed on it was 9.2.1 and the latest software was 9.2.1. • OK, ignore that too. Now it's restoring all my apps, and, wait, i'm getting more error messages, saying that some 96 apps cannot be installed because they cannot be found. What? I have just performed a full USB backup! Probably iTunes didn't backup the apps when doing the backup. That's why it was so fast... • Then, while the restore of music files is in progress, i decide to browse around the new iPad mini, to look and see what's there. So i open iTunes, and it's just all white. I'm connectd to the gogoinflight wifi, without internet, so i figure, maybe it's tryint to connect to the iTunes store and failing. So i put the iPad in Airplane Mode. Now the iPad should know it cannot connect, but it start to pop up the login to iTuens probmpts every second. • OK, so the apps aren't there, just their shadow is there. So i decide to do a second sync, and try to add one App manually. I get the same error, but this time, all the apps in the dock disappear, except one! OK, strange. So i sync again, now the shadow apps in the dock came back. So now i sync again, and they disappear again. Sync again and they stay disappeared. • Eventually i repeat the entire procedure with a better internet connection, and similar simptoms appear. At the end, i still have a bunch of apps which simply didn't restore: they are stuck in that greyed out state, where the only thing one can do, is manually open the App store, and download them. Not possible to simply delete them. • Some other apps restored without an icon! • The restore process didn't even bother to restore many iPhone apps. OK. WTF? Upgrade notice from 9.2.1 to 9.2.1. Now it's iTunes and the playlists. Gone. I was able to restore from a backup, however i lost some information. Just can't rely on Apple software any longer. I'm moving away from iTunes as well now.  Apple software i had to move away from • 2014 Apple Mail: would not connect/synchronize IMAP properly; would not open some messages; would create duplicate emails drafts. • 2015 Apple Calendar: skipped appointment reminders; not able to edit some appointments; new events added on one device would at times not sync to other device. • 2016 Apple Contacts: lost all contacts within Categories; categories still there, just only populated with "company" entries, no persons. • 2015 Apple Photos • 2016 iTunes: lost playlists It's not that hard to get Windows 3 up and running again, if one has the resources to do so. One needs to enter the correct keywords in Google... I've had most success with DOSBox, because it provides with the following advantages over pure virtualization, such as VirtualBox, Parallels or VMWare: • The entire system can be easily packaged up and distributed as a whole. So i can create an optimal configuration for one game, duplicate the entire dosbox folder, and install a a different game that needs different settings on the duplicated folder, and setup win.ini and autoexec.bat to automatically launch the game. Now i have a fully functioning DOS game that i can just double click to launch! • There is a shared folder! No need to setup network, which is very tedious on bare DOS, slightly better on Windows 3.11. • DOS with sound and network already installed. • CPU tweaking on the fly at runtime. Good resources as of 2015 These are links i used to download windows, download word for windows and download other software like drivers and other utilities.      È successo oggi, mentre ero fuori casa. Ha preso fuoco il regolatore di carica. €700 di danno, circa. A giudicare dalle foto, il colpevole è stato il cavo del negativo dei pannelli fotovoltaici, con area troppo piccola.    La App ufficiale 119 di Telecom Italia Mobile promuove un'offerta che non è esistente, con controsenso.   Vedi immagini: Da una parte c'è scritto che si tratta di 1GB aggiuntivo, dall'altra che si tratta solo di 500MB aggiuntivi. Dopo aver attivato la promozione, la verità viene fuori essere solamente 500MB aggiuntivi.  Sul sito web, sembra essere correttamente pubblicizzata come 500MB. Vedi anche   Docker security in the future Interesting article about Docker and security on opensource.com: Docker security in the future   Desktop and Web Page in 2000 First NATed LAN I had two 56k modems, got an extra phone line and had a modem sitting illegally in the office i had at work at the university, taking up a phone line 24/7. The connection was slow, but it was also very cheap. I was sharing it with the neighbors. I built the LAN with old RG-58 cable that they were throwing away at the university. Then i ended up getting an SDSL line, i think it was 1Mbps up, 1Mbps down. 
__label__pos
0.516602
Cheating in Kahoot with AI Cheating in Kahoot with AI I made a program that uses Gemini to cheat in Kahoot. Kahoots are stressing. You're always afraid of losing and must be as fast as possible. But what if it wasn't like that? What if you could cheat, err..., get help from an AI like ChatGPT? That's exactly what I made. (happy new year btw! if you just want the full code, scroll to the end) 🙋 I was advised to warn you to please don't try this at school. This was just a fun experiment and I'm not actually using it to cheat. 💡 This bot only supports True/False and Quiz questions (with or without images) Part 1: The plan So here is the plan: I would build a userscript that would automatically detect when I was playing Kahoot, read the questions, ask Gemini Pro for the answers, and click the button. Optionally, if you didn't want your teacher to notice that you were cheating, the script would change a bit the appearance of the button in a way that your teacher wouldn't notice but you would. For example, change the border-radius, or remove/add a button shadow So, let's get coding. Part 2: The AI I decided to use Google's new Gemini Pro AI for this, as it supported reading images and was smart. We need an API key for this, so follow the instructions: 1. Go to https://makersuite.google.com/ 2. Tap "Get API key" at the left corner 3. Tap "Create new API key in new project" 4. Grab the API key 5. Profit! 💡 If you're not able to access makersuite in your region, just turn on a VPN. I like ProtonVPN. Now, we have the API key and we can continue to the next step. Part 3: Coding 3.1: Detecting when a question is shown Now for the difficult part: coding. I decided to code this in JS, as it was easy and fast. I started by creating a function that would detect when a question is shown on the kahoot quiz: const main = function () { setInterval(function () { if (document.querySelector("button[class*='choice']") && !(document.querySelector("div[class*='extensive-question-title']").getAttribute("done") == "yes")) { getAnswer(); // TODO: Use AI to answer question document.querySelector("div[class*='extensive-question-title']").setAttribute("done", "yes") } }, 100) } main(); This will start an interval that will detect when a choice button is shown and start the whole process. 3.2: Getting the info from the question Now, we need to extract all the information needed for the AI to process the question and generate an answer. After playing with Kahoot's HTML design, I came up with this: const getAnswer = async function () { var question, image = ""; var options = []; if (document.querySelector("img[class*='question-base-image']")) { image = document.querySelector("img[class*='question-base-image']").src; } question = document.querySelector("span[class*='question-title__Title']").innerText.trim(); document.querySelectorAll("button[class*='choice']").forEach(function (e) { var text = e.innerText; options.push(text) }) return await getAI({ question, image, options }); // TODO: Ask AI for the answer and click the button } Nice! Everything works perfectly. Here, we grab the question, the image URL (if an image exists), and the available options, and return everything to a getAI function. 3.3: Getting the answer and clicking the button This step is a bit more tricky. Because Google's Gemini Vision (the model I'm using for when an image is present, else I'm using normal Gemini Pro) requires the image to be in base64, I needed to convert the URL present in Kahoot's HTML and convert it to base64. I found some code in StackOverflow and it worked perfectly: const getAI = async function (data) { /* data: { question: string, image: url, options: array } */ var url, body; function toDataUrl(url) { return new Promise(function (resolve) { var xhr = new XMLHttpRequest(); xhr.onload = function () { var reader = new FileReader(); reader.onloadend = function () { resolve(reader.result); } reader.readAsDataURL(xhr.response); }; xhr.open('GET', url); xhr.responseType = 'blob'; xhr.send(); }) } /* ... */ } Now, let's ask Google's AI for the answer. We'll need to fill the <insert token here> fields with the actual token we got from step 3.1. /* ... */ if (data.image) { const b64 = (await toDataUrl(data.image)).replace("data:", "").split(";base64,"); url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro-vision:generateContent?key=<insert token here>'; // [IMPORTANT] Add your token here body = JSON.stringify({ "contents": [{ "parts": [{ "text": `Answer the following question using the image context provided: ${data.question}. If there are multiple answers and there is no 'All of above/multiple' option, answer a random one. Reply ONLY with the answer that needs to be one of: ${data.options.join("; ")}.` }, { "inline_data": { "mime_type": b64[0], "data": b64[1] } }] }] }); } else { url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=<insert token here>'; // [IMPORTANT] Add your token here body = JSON.stringify({ "contents": [{ "parts": [{ "text": `${data.question}? Reply only with your option. If there are multiple answers and there is no 'All of above/multiple' option, answer a random one. Options: [${data.options.join(", ")}]` }] }] }); } var response = (await (await fetch(url, { method: 'POST', headers: {'content-type': 'application/json'}, body: body })).json()); try { response = response.candidates[0].content.parts[0].text.trim().toLowerCase().replaceAll(".", "").replaceAll(",", ""); } catch { return alert("An error occured. Make sure you're in a supported country. Response:\n\n" + response) } /* ... */ Now, we just need to click the correct button! /* ... */ document.querySelectorAll("button[class*='choice']").forEach(function (e) { var text = e.innerText.trim().toLowerCase().replaceAll(".", "").replaceAll(",", ""); if (text == response) { e.click() } }) return response; } Done! Now let's run everything together in a test Kahoot quiz and the bot will automatically answer all the questions. 3.4: Full code and some warnings First, note that: 1. This code can sometimes be a bit glitchy. 2. This demo won't work in some countries in the EU. If you're in the EU, make sure to turn on a VPN to the US. 3. Don't use this too much or your teacher will notice As promised, here's the full code: const getAI = async function (data) { var url, body; function toDataUrl(url) { return new Promise(function (resolve) { var xhr = new XMLHttpRequest(); xhr.onload = function () { var reader = new FileReader(); reader.onloadend = function () { resolve(reader.result); } reader.readAsDataURL(xhr.response); }; xhr.open('GET', url); xhr.responseType = 'blob'; xhr.send(); }) } // [REQUIRED] Remember to change your API keys. if (data.image) { const b64 = (await toDataUrl(data.image)).replace("data:", "").split(";base64,"); url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro-vision:generateContent?key=<token>'; body = JSON.stringify({ "contents": [{ "parts": [{ "text": `Answer the following question using the image context provided: ${data.question}. If there are multiple answers and there is no 'All of above/multiple' option, answer a random one. Reply ONLY with the answer that needs to be one of: ${data.options.join("; ")}.` }, { "inline_data": { "mime_type": b64[0], "data": b64[1] } }] }] }); } else { url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=<token>'; body = JSON.stringify({ "contents": [{ "parts": [{ "text": `${data.question}? Reply only with your option. If there are multiple answers and there is no 'All of above/multiple' option, answer a random one. Options: [${data.options.join(", ")}]` }] }] }); } var response = (await (await fetch(url, { method: 'POST', headers: {'content-type': 'application/json'}, body: body })).json()); try { response = response.candidates[0].content.parts[0].text.trim().toLowerCase().replaceAll(".", "").replaceAll(",", ""); } catch { return alert("An error occured. Make sure you're in a supported country. Response:\n\n" + response) } document.querySelectorAll("button[class*='choice']").forEach(function (e) { var text = e.innerText.trim().toLowerCase().replaceAll(".", "").replaceAll(",", ""); if (text == response) { e.click() } }) return response; } const getAnswer = async function () { var question, image = ""; var options = []; if (document.querySelector("img[class*='question-base-image']")) { image = document.querySelector("img[class*='question-base-image']").src; } question = document.querySelector("span[class*='question-title__Title']").innerText.trim(); document.querySelectorAll("button[class*='choice']").forEach(function (e) { var text = e.innerText; options.push(text) }) return await getAI({ question, image, options }) } const main = function () { alert("Cheat mode activated"); setInterval(function () { if (document.querySelector("button[class*='choice']") && !(document.querySelector("div[class*='extensive-question-title']").getAttribute("done") == "yes")) { getAnswer(); document.querySelector("div[class*='extensive-question-title']").setAttribute("done", "yes") } }, 100) } main(); Should this be banned from Kahoot? Post your opinions in the comments. Thanks for reading! Remember to leave a like
__label__pos
0.999874
3.1 Inputs with attributes using composed_of ilyakatz edited this page Aug 7, 2011 · 1 revision If model uses composed_of to convert an attribute to manipulate the value of the attribute symantic_form_for may not present the value of the field properly. Here is an example of how to add money money (using money gem) # encoding: utf-8 module Formtastic class SemanticFormBuilder def money(method, options = {}) value = object.send(method).format(:no_cents_if_whole => true, :symbol=>false) new_input_html = options[:input_html] ? {:value=>value}.merge(options[:input_html]) : {:value=>value} options[:input_html]=new_input_html input(method, options) end end end After that, you can use form.money as any other input <%= semantic_form_for @new_rate || Rate.new() do |form| %> <%= form.money :value %> <% end %>
__label__pos
0.966516
如何在Delphi中获取完全合格的域名 我需要在Delphi中获取域上的Windows机器的完全合格的域名 我试图使用LookupAccountSid,但它只给我netbios域名,在我的情况下,它是“内联网”,但我需要充分的“intranet.companyname.com” 有任何想法吗? Solutions Collecting From Web of "如何在Delphi中获取完全合格的域名" 尝试GetUserNameEx Windows API函数。 const NameUnknown = 0; NameFullyQualifiedDN = 1; NameSamCompatible = 2; NameDisplay = 3; NameUniqueId = 6; NameCanonical = 7; NameUserPrincipal = 8; NameCanonicalEx = 9; NameServicePrincipal = 10; NameDnsDomain = 12; function GetUserNameExString(ANameFormat: DWORD): string; var Buf: array[0..256] of Char; BufSize: DWORD; GetUserNameEx: function (NameFormat: DWORD; lpNameBuffer: LPSTR; var nSize: ULONG): BOOL; stdcall; begin Result := ''; BufSize := SizeOf(Buf) div SizeOf(Buf[0]); GetUserNameEx := GetProcAddress(GetmoduleeHandle('secur32.dll'), 'GetUserNameExA'); if Assigned(GetUserNameEx) then if GetUserNameEx(ANameFormat, Buf, BufSize) then Result := Buf; end; 使用NameDnsDomain格式,例如,如果您登录到“www.mydomain.com”域,将导致www.mydomain.com\user_name 由于我现在在我们的应用程序中为自己的需要实现了这个功能,@ iPath的评论是正确的。 更好地使用GetComputerNameEx ,并根据自己的需要指定一个COMPUTER_NAME_FORMAT Delphi实现看起来像这样(Unicode版本): interface ... type COMPUTER_NAME_FORMAT = ( ComputerNameNetBIOS, ComputerNameDnsHostname, ComputerNameDnsDomain, ComputerNameDnsFullyQualified, ComputerNamePhysicalNetBIOS, ComputerNamePhysicalDnsHostname, ComputerNamePhysicalDnsDomain, ComputerNamePhysicalDnsFullyQualified, ComputerNameMax); function GetComputerNameExString(ANameFormat: COMPUTER_NAME_FORMAT): WideString; implementation ... function GetComputerNameExW(NameType: COMPUTER_NAME_FORMAT; lpBuffer: LPWSTR; var nSize: DWORD): BOOL; stdcall; external kernel32 name 'GetComputerNameExW'; function GetComputerNameExString(ANameFormat: COMPUTER_NAME_FORMAT): WideString; var nSize: DWORD; begin nSize := 1024; SetLength(Result, nSize); if GetComputerNameExW(ANameFormat, PWideChar(Result), nSize) then SetLength(Result, nSize) else Result := ''; end; NetGetJoinInformation应该可以正常工作。 MSDN: http://msdn.microsoft.com/en-us/library/windows/desktop/aa370423(v=vs.85).aspx 例: type PWKSTA_INFO_100 = ^WKSTA_INFO_100; WKSTA_INFO_100 = packed record wki100_platform_id: DWord; wki100_computername: PWChar; wki100_langroup: PWChar; wki100_ver_major: DWord; wki100_ver_minor: DWord; end; TNetSetupJoinStatus = ( NetSetupUnknownStatus, NetSetupUnjoined, NetSetupWorkgroupName, NetSetupDomainName ); TNetApiBufferFreeFunction = function(ABuffer: Pointer): DWORD; stdcall; TNetWkstaGetInfoFunction = function(const Aservername: PWChar; const ALevel: DWord; const ABufptr: Pointer): DWORD; stdcall; TNetGetJoinInformationFunction = function(const AserverName: PWChar; out ANameBuffer: PWChar; out ABufferType: TNetSetupJoinStatus): DWORD; stdcall; const NERR_SUCCESS = 0; function GetLocalComputerDomainName: string; var NetApiBuffer: Pointer; NetApi: THandle; NetApiBufferFree: TNetApiBufferFreeFunction; NetWkstaGetInfo: TNetWkstaGetInfoFunction; NetGetJoinInformation: TNetGetJoinInformationFunction; NetSetupJoinStatus: TNetSetupJoinStatus; NameBuffer: PWideChar; begin Result := ''; NetApi := LoadLibrary('netapi32.dll'); if NetApi <> 0 then begin NetApiBufferFree := TNetApiBufferFreeFunction( GetProcAddress(NetApi, 'NetApiBufferFree')); NetGetJoinInformation := TNetGetJoinInformationFunction(GetProcAddress(NetApi, 'NetGetJoinInformation')); NetWkstaGetInfo := TNetWkstaGetInfoFunction( GetProcAddress(NetApi, 'NetWkstaGetInfo')); if @NetApiBufferFree <> nil then begin if @NetSetupJoinStatus <> nil then begin if NetGetJoinInformation(nil, NameBuffer, NetSetupJoinStatus) = NERR_SUCCESS then begin if NetSetupJoinStatus = NetSetupDomainName then begin Result := NameBuffer; end; NetApiBufferFree(NameBuffer); end; end; end; FreeLibrary(NetApi); end; end; 我尝试了以上所有,但没有成功。 最后,我决定只是抓住环境变量。 uses jclSysInfo; function GetDomain:string; begin result:=GetEnvironmentVariable('USERDNSDOMAIN'); end; 测试服务器2008 R2 – 工作正常。 返回“server.home.lan”。 在Windows 7非域连接的PC上产生一个空字符串。
__label__pos
0.936452
FlexGAM: Generalized Additive Models with Flexible Response Functions Standard generalized additive models assume a response function, which induces an assumption on the shape of the distribution of the response. However, miss-specifying the response function results in biased estimates. Therefore in Spiegel et al. (2017) <doi:10.1007/s11222-017-9799-6> we propose to estimate the response function jointly with the covariate effects. This package provides the underlying functions to estimate these generalized additive models with flexible response functions. The estimation is based on an iterative algorithm. In the outer loop the response function is estimated, while in the inner loop the covariate effects are determined. For the response function a strictly monotone P-spline is used while the covariate effects are estimated based on a modified Fisher-Scoring algorithm. Overall the estimation relies on the 'mgcv'-package. Version: 0.7.0 Depends: R (≥ 3.4.0), mgcv (≥ 1.8-23) Imports: graphics, MASS, Matrix, scam, splines, stats Published: 2018-02-21 Author: Elmar Spiegel [aut, cre] Maintainer: Elmar Spiegel <espiege at uni-goettingen.de> License: GPL-2 NeedsCompilation: no Materials: NEWS CRAN checks: FlexGAM results Downloads: Reference manual: FlexGAM.pdf Package source: FlexGAM_0.7.0.tar.gz Windows binaries: r-devel: FlexGAM_0.7.0.zip, r-devel-gcc8: FlexGAM_0.7.0.zip, r-release: FlexGAM_0.7.0.zip, r-oldrel: FlexGAM_0.7.0.zip OS X binaries: r-release: FlexGAM_0.7.0.tgz, r-oldrel: FlexGAM_0.7.0.tgz Linking: Please use the canonical form https://CRAN.R-project.org/package=FlexGAM to link to this page.
__label__pos
0.60588
top of page Python Practice Set January 2023 Updated: Dec 31, 2022 1. The output of the following code. string=”my name is x” for i in string: print(i,end=”,”) A. m,y,,n,a,m,e,,i,s,x, B. m,y,,n,a,m,e,,i,s,x C. my,name,is,x D. None Answer: (A) 2. What arithmetic cannot be used with strings? A. + B. * C. D. All of the mentioned Answer: (C) 3. The output of the following code. string=”my name is x” for i in string.split(): print(i,end=”, ”) A. m,y,,n,a,m,e,,i,s,,x, B. m,y,,n,a,m,e,,I,s,,x C. my,name,is,x, D. Error Answer: (C) 4. The output of the following code. a=[0,1,2,3] for a[-1] in a: print(a[-1]) A. 0 1 2 3 B. 0 1 2 2 C. 3 3 3 3 D. error Answer: (B) 5. The output of the following code. a=[0,1,2,3] for a [0] in a: print(a[0]) A. 0 1 2 3 B. 0 1 2 2 C. 0 2 3 4 D.Error Answer: (A) 6. The output of the following code. a=[0,1,2,3] i= -2 for i in not in a: print(i) i+=1 A. -2 -1 B. 0 C. Error D.None of the mentioned Answer: (C) 7. The output of the following code. >>>”b”+”cde” A. a B. cde C. bcd D.Bcde Answer: (D) 8. The output of the following code. >>>”abcde”[3 :] A. ab B. de C. cde D.None Answer: (B) 9. The output of the following code. >>>print(‘new’ ‘line’) A. error B. output equialent to print ‘newline’ C. newline D.new line Answer: (D) 10. The output of the following code. >>>max(“what are you”) A. u B. t C. m D.K Answer: (A) 11. Which of the following statement prints helloexample test.txt? A. print(“helloexample est.txt”) B. print(“helloexample test.txt”) C. print(“hello”example”test.txt”) D.print(“hello”example “est.txt”) Answer: (B) 12. The output of the following code. print(“xyyzxyzxzxyy”.count(‘yy’)) A. 3 B. 0 C. 2 D.None Answer: (C) 13. The output of the following code. >>>str1=”helloworld” >>>str1[: : -1] A. dlrowolleh B. Hello C. world D.Helloworld Answer: (A) 14. what is the output of the below program in python: print(0.2+0.4==0.6) A. True B. False C. Error D.Depends on machine Answer: (B) 15. Which is not a feature of python language. A. interpreted language B. portable C. high level language D.case insensitive Answer: (D) 16. Python is a …………object-oriented programming language. A. Special purpose B. General purpose C. Medium level programming language D.All of the mentioned above Answer: (D) 17. Developer of python programming? A. Denis Ritchie B. Y.C Khenderakar C. Tim Berner Lee D.Guido van Rossum Answer: (D) 18. Which are application areas of python programming? A. Web development B. Game development C. Artificial intelligence and machine learning D. All of the above Answer: (D) 19. What is numeric types of data types? A. int B. Float C. Complex D.All of the above Answer: (D) 20. What is the output for below code? a = 2 b = 3 print(a,b) a,b=b,a print(a,b) A. 23 23 B. 23 32 C. 32 32 D.None of above Answer: (B) 21. List tuple dictionary are which types of datatypes? A. Binary types B. Boolean types C. Sequence types D.None of the above Answer: (C) 22. Which keyword used in python language? A. Finally B. Lambda C. While D.All of above Answer: (D) 23. Python Dictionary is used to store the data in. A. Key value pair B. Set value pair C. Tuple value pair D.None of the above Answer: (A) 24. Which is invalid variable? A. my_string_1 B. _ C. Foo D.1st_string Answer: (D) 25. What is the output of given code? 4+2**5//10 A. 77 B. 7 C. 3 D.0 Answer: (B) 26. The python language developed in which? A. 1995 B. 1989 C. 1972 D.1981 Answer: (B) 27. Single line comment in python? A. / B. // C. # D.! Answer: (C) 28. Conditional statements are also known as. A. Decision-making B. Array C. List D.Looping Answer: (A) 29. Which is not used as Conditional statement in python? A. switch B. if…else C. elif D.For Answer: (A) 30. which string represent the purpose for which the file is open? A. “file name” B. “file handle” C. “file mode” D.None of above Answer: (C) 31. File handle is also know as. A. File name B. File variable C. File object D.none of above Answer: (C) 32. which () finf the current position of file pointer with in file? A. Seek() B. Tell() C. Read() D.All of above Answer: (B) 33. What is packing. A. it is used for object serialization B. It is used for object deserialization C. All of the mentions D.None of above Answer: (A) 34. Eof standed for. A. End of file B. End of close C. End of open D.None of them Answer: (A) 35. Input device. A. Headphone B. Gps C. Microphone D.All of above Answer:(C) 36. To reped the list up to a spacify a number of iteam. Which operater required? A. + B. * C. : D.None Answer:(C) 37. What type of data is? a=[(1,1),(2,5),(3,9)] A. array of tuple B. tuples of list C. List of tuple D.invalid list Answer:(C) 38. What will be print? Import numpy as np a = np. array([1,2,3,5,8]) b = np. array([0,3,4,2,1]) c = a+b c = c*a print(c[2]) A. 7 B. 12 C. 10 D. 21 Answer: D 39. import numpy as np. a = np.array([[1,2,3],[0,1,4]]) print(a.size) A. 1 B. 5 C. 6 D. 4 Answer: C 40. import numpy as np a = np.array([1,2,3,5,8]) print(a.ndim) A. 0 B. 1 C. 2 D. 3 Answer: B 41. Numpy stands for. A. Numbering Python B. Number in Python C. Numerical Python D. Number Python Answer: C 42. numpy is used along with package like? A. Node Js B. Matplotlib C. Scipy D. Both(B)and(C) Answer: D 43. the sets the size of the buffer used in ufuncs? A. bufsize(size) B.setsize(size) C. set bufsize(size) D. Size(size) Answer: C 44. import numpy as np dt=dt= np.dtype(‘i,4’) print(dt) A. int 32 B. int 64 C. int 128 D. int 16 45. if a dimension is given as _ in a reshaping operation, the other dimensions are Automate cally calculated. A. Zero B. One C. Negative one D. Infinite Answer: (C) 46. Testing process first goal. A. Testing B. Analysis C. Bug preventation D. All of above Answer: (C) 47. Sorting means. A. Arranging the data B. Processing the data C. Calegrizing D.None of above Answer: (A) 48. Medium of comonunication. A. Network B. Compiler C. Language D.All of above Answer: (C) 49. Bug means. A. An insert in the program B. Data input to the program C. The error in the program D.All of the above Answer: (C) 50. Identifire maxium possible lenth. A. 31 character B. 63 character C. 79 charater D.None of the above Answer: (C) 51. Which of the following is an invalid variable. A. my_string_1 B. 5 st_string C. Too D.__ Answer: (B) 52. Which function do you use to read a string? A. input(“enter a string”) B. eval(input(“enter a string”)) C. enter(“enter a string”) D.eval(enter(“enter a string”)) Answer: (A) 53. What will be the output of the following python code? print(“abc DEF”.capitalize()) A. abc def B. ABC DEF C. Abc def D. Abc Def Answer: (C)
__label__pos
1
/* * Based on arch/arm/kernel/sys_arm.c * * Copyright (C) People who wrote linux/arch/i386/kernel/sys_i386.c * Copyright (C) 1995, 1996 Russell King. * Copyright (C) 2012 ARM Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * 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 . */ #include #include #include #include #include #include #include #include static long __do_compat_cache_op(unsigned long start, unsigned long end) { long ret; do { unsigned long chunk = min(PAGE_SIZE, end - start); if (fatal_signal_pending(current)) return 0; ret = __flush_cache_user_range(start, start + chunk); if (ret) return ret; cond_resched(); start += chunk; } while (start < end); return 0; } static inline long do_compat_cache_op(unsigned long start, unsigned long end, int flags) { if (end < start || flags) return -EINVAL; if (!access_ok(VERIFY_READ, start, end - start)) return -EFAULT; return __do_compat_cache_op(start, end); } /* * Handle all unrecognised system calls. */ long compat_arm_syscall(struct pt_regs *regs) { unsigned int no = regs->regs[7]; switch (no) { /* * Flush a region from virtual address 'r0' to virtual address 'r1' * _exclusive_. There is no alignment requirement on either address; * user space does not need to know the hardware cache layout. * * r2 contains flags. It should ALWAYS be passed as ZERO until it * is defined to be something else. For now we ignore it, but may * the fires of hell burn in your belly if you break this rule. ;) * * (at a later date, we may want to allow this call to not flush * various aspects of the cache. Passing '0' will guarantee that * everything necessary gets flushed to maintain consistency in * the specified region). */ case __ARM_NR_compat_cacheflush: return do_compat_cache_op(regs->regs[0], regs->regs[1], regs->regs[2]); case __ARM_NR_compat_set_tls: current->thread.tp_value = regs->regs[0]; /* * Protect against register corruption from context switch. * See comment in tls_thread_flush. */ barrier(); asm ("msr tpidrro_el0, %0" : : "r" (regs->regs[0])); return 0; default: return -ENOSYS; } }
__label__pos
0.998628
cancel Showing results for  Show  only  | Search instead for  Did you mean:  Aspiring Contributor 338 Views Message 1 of 6 old cabe v new cat 6 hi all have been testing the results of the 2 cables going to hh5 on 5gh ssid and thought the new cable would have been worth the buy !! i have had the older cable for 5 years when we got adsl installed  these were tested wirelessly on iphone 6 first pic is of the cat 6  and 2nd pic of old cable new cat 6.PNG old cable.PNG 0 Ratings 5 REPLIES 5 Distinguished Sage Distinguished Sage 325 Views Message 2 of 6 Re: old cabe v new cat 6 I think I must be missing something but what have the different cables got to do with a wifi conenction and test? If you like a post, or want to say thanks for a helpful answer, please click on the Ratings 'Thumbs up' on left hand side. If someone answers your question correctly please let other members know by clicking on ’Mark as Accepted Solution’. 0 Ratings Distinguished Sage Distinguished Sage 312 Views Message 3 of 6 Re: old cabe v new cat 6 @imjolly wrote: I think I must be missing something but what have the different cables got to do with a wifi conenction and test? I wondered the same but assumed he meant the cable from phone socket to the HH5. 0 Ratings Distinguished Sage Distinguished Sage 307 Views Message 4 of 6 Re: old cabe v new cat 6 @gg30340 wrote: @imjolly wrote: I think I must be missing something but what have the different cables got to do with a wifi conenction and test? I wondered the same but assumed he meant the cable from phone socket to the HH5. Thought the same but have found it dangerous to assume so decided to ask the question  If you like a post, or want to say thanks for a helpful answer, please click on the Ratings 'Thumbs up' on left hand side. If someone answers your question correctly please let other members know by clicking on ’Mark as Accepted Solution’. 0 Ratings Distinguished Sage Distinguished Sage 305 Views Message 5 of 6 Re: old cabe v new cat 6 Agreed and that's why I never bothered to reply. 0 Ratings Expert 301 Views Message 6 of 6 Re: old cabe v new cat 6 Do you mean the cable from the wall socket to the HH?   There is quite a different in speed - I don't think this can be down to the cable.   If you have tested speed before has it always been around the 20Mbps mark?   The best way to test speed is via a device connected via ethernet to the HH, but having said that 76Mbps is a good speed.   What speed are you paying for BTW? 0 Ratings
__label__pos
0.534658
The tag has no wiki summary. learn more… | top users | synonyms 0 votes 1answer 203 views Where on the disk is the NTFS reserved area? By default on a freshly installed system with plenty of free space on a disk, where are the NTFS reserved area located on the disk? What percentage of the way through the disk is it located at? ... 1 vote 1answer 480 views Creating Windows PE boot cd with MyDefrag As I would like to defrag the unmovable files. As far as I understend it is possible to do by running Windows PE. What is the easiest way of creating custom Windows PE image? 0 votes 1answer 105 views Can someone explain to me use of MyDefrag flash script? Can someone explain to me use of MyDefrag flash script? I read the article on MyDefrag's site, but the concept is still unclear to me. What exactly is that extra processing needed? 1 vote 0answers 440 views Defrag Scripts for MyDefrag I'm looking for some fairly good (viewable results) and/or popular defrag scripts for MyDefrag. Can someone direct me to some, pretty please? 0 votes 1answer 932 views MyDefrag Script: Shutdown after Completion? I'm looking for a script that shuts down my PC after it completed the procedure. Preferably inside the standard scripts! 2 votes 3answers 2k views Why does MyDefrag take so long to Fast Optimize? From recommendations in other questions about defragmenters, I decided to try out MyDefrag. However I'm finding that the Fast Optimize script is running very slowly, specifically it seems to take a ...
__label__pos
0.986809
Understanding the Logic of System Testing An Approach to Constructing AValid Proof Constructing a valid proof in system testing can be defined as a four-step procedure. The following sections discuss each step in detail, and explain how to construct a valid argument to support a testing conclusion. Step 1: Define a Conclusion of the Argument In constructing a proof, always begin by defining what needs to be proven, i.e., the conclusion. In system testing, the ultimate goal is to evaluate a software product. This is achieved by decomposing the entire functional domain into a set of functional features where each feature to be tested is a unit of a tester's work that results in one of the two possible conclusions about a feature’s testing status pass or fail. At any given time, only one of the two conclusions is valid. The term software feature is defined in the IEEE Std. 610 as follows: • A distinguished characteristic of a software item. • A software characteristic specified or implemented by requirements documentation. From a tester’s perspective, a software feature means any characteristic of a software product that the tester believes might not work as expected and, therefore, should be tested. Deciding what features should be in the scope of testing is done at the test-planning phase and documented in a test File:  About the author Yuri Chernak's picture Yuri Chernak Yuri Chernak, Ph.D, is the president and principal consultant of Valley Forge Consulting, Inc. Yuri has worked for a number of major financial firms in New York, leading QA governance committees in IT and helping clients improve their software requirements and software testing practices. Yuri is a pioneer in implementing a new discipline—aspect-oriented requirements engineering—for financial applications on Wall Street. He is a member of the IEEE Computer Society, has been a speaker at several international conferences in the US and Canada, and has published papers in the IEEE publications and other professional journals. Contact Yuri at [email protected].
__label__pos
0.589349
Lesson 1 - Introduction to object-oriented programming in VB.NET Welcome to the first lesson of the object-oriented Visual Basic .NET programming course. We finished the VB.NET basic constructs course last time with the article about Mathematical functions in VB.NET. In this course, you'll learn to program in an object-oriented way and will also develop an object-oriented way of thinking. It's a bit different than anything we've done until now. For starters, we will no longer treat programs like several lines of code that the interpreter executes one by one. The invention of object-oriented programming, OOP hereinafter, was no coincidence, but the result of a development which led to its creation. It's a modern software development methodology supported by most programming languages. A common mistake is that people think that OOP should only be used for certain kinds of programs and that for other cases it would be needlessly complicated; however, the opposite has proven to be true. OOP is a philosophy. It's a new way of looking at a program and the communication between its parts. We should always use it whenever we create a simple utility or a complex database system. The OOP is not just a technology or a recommended program structure, it's mainly a new way of thinking. A new perspective from which we could analyze problems and a new era in software development. As first, we'll look quickly into the history of how people programmed before OOP and what specific problems OOP resolves. It's important for us to fully understand why the OOP had to be created. The evolution of methodologies There is a big difference between programming nowadays and programming 40 years ago. The first computers didn't have great performance and their software was quite simple. The evolution of hardware is so fast that the number of transistors in microprocessors doubles every year (Moore's Law). Unfortunately, people aren't able to evolve as quickly as hardware does. Faster computers require more and more sophisticated and complex software (people want more and more from their computers). So much that at one point, it was found out that about 90% of all software doesn't meet deadlines, requires additional costs or isn't finished at all. Developers started looking for new ways to write programs. Several new approaches took turns. More precisely, paradigms (ways of thinking). Listed as follows: 1. Machine code The program was just a set of instructions where we weren't able to name variables or enter mathematical expressions. The source code was obviously specific for the then current hardware (processor). This paradigm was replaced soon after it was established. 2. The unstructured paradigm The unstructured approach is similar to the assembly languages, it's a set of instructions which are executed line by line. The source code wasn't dependent on the hardware and was human readable. This approach enabled the creation of more complex programs for a while. There were still many pitfalls: the only way to repeat something or to branch off a code was the GOTO statement. GOTO allowed to "jump" to different locations within the program. Locations were previously specified by a line number in the source code, which is obviously impractical. When we insert a new line of code somewhere, the numbers no longer match and the code is broken. Later, it was made possible to define what they then called "labels". This approach served as a way of simulating loops. This method of writing programs is of course very confusing and soon failed to be sufficient for developing complex programs. Consider that the huge adoption of personal computers over the past few decades caused the growth of software demand and, naturally, a demand of more people who make programs (programmers). Certainly, there are people who can write bulletproof programs even in ASM or other low-level languages, but how many are there? How much does this superhuman job cost? It's necessary to write programs in a way that even less experienced programmers could write high-quality programs and not need to go through 5 years of experience to code a simple utility app. 3. The structured programming Structured programming is the first paradigm that lasted for a longer time and was quite sufficient for the development of new programs. They would mostly program using loops and branching. Conceptually, we are in the structured programming era based on what we have learned from the first course. The program would be decomposed into functions, methods, that we haven't discussed yet since Visual Basic .NET, which is an object-oriented language, doesn't even allow us to declare them. There is a way to do it anyway, but I'd rather skip this intermediate step and get right into OOP. In structured programming, we meet a functional decomposition principle. A problem is decomposed into several subproblems and each subproblem is then solved with some parametrized function. The disadvantage to it is that a function can only do one thing and when we want a different behavior, we have to write a new one. There is no way to reuse old code and modify it. We need to write it again and again - this creates unnecessary, potentially costly, errors. This disadvantage can be partially worked around by using parametrized functions or using global variables. However, such universal functions usually require a lot of parameters to pass and are hard to use and maintain. With global data, there's another pitfall. Functions can access the data of other functions. This is the beginning of the end, we can't guarantee that global data isn't being overwritten somewhere between functions. It leads to uncontrollable problems. The entire program will consist of unencapsulated code blocks and can hardly be maintained. Any modification increases the complexity of the program, and then the program will necessarily come to a situation where the cost of adding new features will overbalance the value added by these features. Languages using this approach are, for example, the C language and Pascal. Between the structured programming and the object-oriented programming, there was one more intermediate approach called modular programming. It involved the encapsulation of specific functionality into modules. Regardless, there was no way to modify and reuse already written code. As I mentioned at the beginning of the article, it's sometimes said that simple programs mustn't be written in an object-oriented way, but structural, which isn't true. If we program in a structural fashion, we will end up making a blob that will be almost unreadable by most people. Then again, it would come to a point where the program wouldn't even be upgradable and we'd either have to throw it away or rewrite it using the OOP. The non-object-oriented methods of writing code are called "spaghetti code" because of their lack of clarity (everything is tangled together like spaghetti). The object-oriented approach OOP is a philosophy and a way of thinking, designing and implementing solutions that focuses on reusability. This approach is inspired by the industrial revolution - the invention of basic components. For example, when we build our house, we don't burn our own bricks and forge nails, we order them. Making a "component program" is smarter and cheaper. Components don't fail, they're tested and maintained. If there's a problem, it is most likely in the code you have written in one specific location. We're motivated to write clear code since it can be used by others or by ourselves in other projects. Let's face it, humans are lazy by nature and if we thought that our code wouldn't ever be reused, we simply wouldn't write it good enough :) ). Of course, we'll use the knowledge we have gained until now. The main difference is that now, our code will be structured differently into multiple communicating objects. How the OOP works It tries to simulate reality as we're used to see it. We can say that we abandon the idea how the program is seen by the computer (machine) and write it from the programmer's (human's) point of view. As we had replaced the assembler with human-readable mathematical notations, now we're going even further and replace those, too. OOP is, therefore, a certain level of abstraction above the program. This has significant advantages because it's more natural and readable for us. The basic component is object which corresponds with some object from the real world, e.g. a human object or a database object). Objects in object-oriented programming in Visual Basic .NET Objects have attributes and methods. Attributes Object attributes are properties or data that it stores, e.g. the human's name and age. For the database object it could be the password or whatever the objects requires to work. Attributes are just like ordinary variables with which we've worked a hundred times. Sometimes they're called the "object's internal state". The term "property" was reserved by Microsoft for some specific usage and the same is with the term "attribute". Object variables are called "fields" in C# .NET. However, other languages often call them properties (PHP) or attributes (Java) and I might call them attributes as well in further texts. Methods Methods are abilities that the object can perform. Human, for example, could have the methods GoToWork(), Greet() or Blink(). For the database, it could be AddEntry() or Search(). Methods can have parameters and can also return values (we call those functions in VB.NET). You've actually used them before without even knowing! Remember the Split() method on the String object? A String is actually an object that represents text. You can see that we can easily imagine that we're dealing with text. We can modify it, ask it to return its length, combine it with other strings, etc.. It contains methods that a text can perform, copying, deleting, splitting, and also has fields, e.g. Length which contains its length. Class attributes and methods in the object-oriented programming in VB.NET In older languages, methods didn't belong to objects but were loosely placed in modules (units). We could call them by typing Split(text) instead of text.Split(). The disadvantage to that was, of course, that the Split() method didn't belong to anything. There was no way to list what String could do and the code was messy. Additionally, we couldn't have two methods with the same name. In OOP we can have both user.Remove() and article.Remove(). It's very clear and simple. In a structured program we'd have to write: remove_user(user) and remove_article(ar­ticle). We'd have to create thousands of silly, unnecessary methods. If you're thinking, hey, isn't that what the PHP language does? You are absolutely right. PHP is terrible when it comes to things like this, and for that same reason, its design is considered old. It became fully object-oriented later, but its foundations will probably never change. VB.NET is a modern language and the .NET framework is strongly built on objects. In this article, we're going to explain the basics of how to create objects and how to encapsulate their internal logic. Other OOP features, mainly inheritance, will be explained in the following lessons, to not overload your brain today :) Class We have already encountered the term "class". We understood it as a set of commands. A class, however, allows us to do so much more. A class is a pattern that we use to create objects. It defines their properties and abilities. An object created according to a class is called an instance. Instances have the same interface as the class according to which they were created, but they mutually differ in their internal data (fields). For example, let's consider a Human class and creating the carl and jack instances from it. Both instances will have the same fields as the class (e.g. name and age) and methods (goToWork() and greet()), but the values in them will be different. For example, the first instance will have the value "Carl" in the name attribute and 22 in age, the second will have the values Jack and 45. Class vs. instance The communication between objects is performed by messaging which makes the syntax clear. The message usually looks like this: recipient.methodName(parameters). For example, carl.greet(neighbor) could cause the carl instance to greet the neighbor instance. OOP is based upon three core concepts: • encapsulation • inheritance • polymorphism Let's look into the first of them: Encapsulation Encapsulation allows us to hide some methods and fields so they can remain available only from inside of the class. The object can be thought of as a black box that provides an interface through which we can pass instructions/data to be processed by it. We don't know how the object works internally, but we know how it behaves on the outside and how we should use it. We can't cause errors because we are only allowed to use it in a way its creator meant it to be used. An example might be the Human class having a birthDate field and a few more based on its value: fullAged and age. If someone changed birthDate from outside the object, the values in fullAged and age variables could become invalid. Which means that the internal state of the object would be inconsistent. This could happen to us in structured programming. In OOP, however, we encapsulate the object and mark the birthDate attribute as private so it won't be visible from the outside. To the outside, we'd provide a ChangeBirthDate() method which would store a new birth date into a birthDate variable and also perform a necessary age re-calculation and full-age re-valuation. Using the object would be always safe and the application stable. Encapsulation forces programmers to use objects only in the right way. The class interface is divided into publicly accessible (public) and internal (private) members. In the next lesson, First object-oriented application in VB - Hello object world, we'll create our first object-oriented program.   All articles in this section Object-Oriented Programming in VB.NET Skip article (not recommended) First object-oriented application in VB - Hello object world Article has been written for you by Michal Zurek Avatar User rating: 2 votes Activities     Comments Avatar Stafford Campbell:4/25/2018 6:06 So far, straightforward and clear, It is a recap of much that I already know, but useful all the same.   Reply 4/25/2018 6:06 Avatar Nelson Keboutlule:6/9/2020 7:46 This lesson was great.   Reply 6/9/2020 7:46 To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free. 2 messages from 2 displayed.
__label__pos
0.967886
Why does JavaScript variable declaration at console results in “undefined” being printed? I have already read the following SO posts: Why does this JavaScript code print “undefined” on the console? Why does Chrome & FireFox console print undefined? Why does the JS console return an extra undefined? But none of it explains why the JavaScript console prints undefined when I declare a variable as follows: var a; Answers: Answer It prints the result of this expression - which is undefined. And yes, var a is a valid expression on its own. Actually, you should rather be amused by why console prints undefined when you write var a = 3 or something like this. It also prints undefined if function anyFunctionName() {} statement is processed. In fact, all the var and function declaration (!) statements seem to be ignored if there's another statement with some 'real' result: >>> var a = 3; undefined >>> var a = 3; a = 4; 4 >>> var a = 3; a = 4; var a = 5; function f() {}; 4 // !!! Now, I suppose the real reason behind is behaviour of eval statement, as described here: • Let result be the result of evaluating the program prog. • If result.type is normal and its completion value is a value V, then return the value V. • If result.type is normal and its completion value is empty, then return the value undefined. So now the question is, what does var a = 4 statement return? Guess what: it's not 4. The production VariableStatement : var VariableDeclarationList; is evaluated as follows: • Evaluate VariableDeclarationList. • Return (normal, empty, empty). Now the most interesting part: what happened in the last example, why 4 is the result? That's explained in this section: The production Program : SourceElements is evaluated as follows: • Let result be the result of evaluating SourceElements. [...] The production SourceElements : SourceElements *SourceElement* is evaluated as follows: • Let headResult be the result of evaluating SourceElements. • If headResult is an abrupt completion, return headResult. • Let tailResult be result of evaluating SourceElement. • If tailResult.value is empty, let V = headResult.value, otherwise let V = > tailResult.value. • Return (tailResult.type, V, tailResult.target) Both function f() {} and var a = 5 statements' return values were (normal, empty, empty). So the script ended up with giving out the result of the first statement (starting from the script's end, so technically it's the last one) that's not (normal, empty, empty). That is the result of a = 4 assignment statement - which is 4. P.S. And now for some icing on the cake: consider the following: >>> function f() {} undefined >>> (function f() {}) function f() {} The difference is quite subtle: the first input is treated as a Function Declaration statement, which, according to this rule... The production SourceElement : FunctionDeclaration is evaluated as follows: • Return (normal, empty, empty). ... will eventually produce undefined when eval-ed, as we already know. The second input, however, is treated as a Function Expression, which is evaluated to the function itself. That means it'll be passed through eval and eventually returned to the console (in its format). Answer var a=1; a gives: 1 while var a=1; gives: undefined in the first case the console evaluates a so it prints the value of a in the second case the console does not evaluate the value of a, but it evaluates the expression itself. Answer because all you are doing is declaring there is a variable - what is it? a string, an integer, a boolean - we don't know yet - hence undefined Tags Recent Questions Top Questions Home Tags Terms of Service Privacy Policy DMCA Contact Us ©2020 All rights reserved.
__label__pos
0.999002
Coding4Fun Articles - Channel 9 Coding4Fun articles detail interesting applications we created using a variety of programming languages. Most articles assume a basic understanding of the utilized language, but if you need help, please ask—we’ll do our best to help out. Microsoft [email protected] no https://sec.ch9.ms/content/feedimage.png Coding4Fun Articles - Channel 9 https://s.ch9.ms/coding4fun/articles Coding4Fun articles detail interesting applications we created using a variety of programming languages. Most articles assume a basic understanding of the utilized language, but if you need help, please ask—we’ll do our best to help out. https://s.ch9.ms/coding4fun/articles en Sat, 25 Mar 2017 12:13:26 GMT Sat, 25 Mar 2017 12:13:26 GMT Rev9 279 12 25 Getting started with Cinder for Windows Store Apps What is different on Windows 8 Legacy software written for Windows 7 and prior targeted the traditional Windows API, often referred to as Win32. They resulting apps would be a combination of an executable, assets and libraries. The Windows 8 operating system introduces a new type of application, called a Windows Store app. The new architecture is called Windows Runtime, or WinRT for short. Windows Store apps are written exclusively against this new WinRT architecture. Windows 7 and prior only had one mode of interacting with software, launching the application's executable from the desktop or file path. Windows 8 now defaults to a Windows Runtime start screen, where Windows Store apps are presented and can be accessed through their respective Live Tiles. An application's Live Tile is registered automatically when that app is installed from the Windows Store. If a user needs to access legacy software that hasn't been migrated to the new Windows Store format, they can still get to the desktop from the Start Screen. Windows desktops and laptops have traditionally run on Intel processors, referred to frequently as x86 or x64 machines. However, in parallel with the release of Windows 8, an optimized version of the operating system designed for mobile ARM based devices was released called Windows RT. Windows RT devices, however, will not run legacy Win32 software, nor can you develop Win32 software for content. So unlike a Windows 8 computer, which is optimized for the Windows Store apps written against WinRT but still provides access to Win32 software from the desktop, Windows RT devices do not. What about the Microsoft Surface? There are two versions of the Microsoft Surface. The first version runs the Windows RT operating system and uses an ARM CPU. The Surface Pro, however, is an x64 device and runs Windows Pro 8. Both devices are optimized for Windows Store apps, but the Surface Pro is a fully featured computer as well, allowing you to install Visual Studio, Photoshop, or whatever else you wish. You can think of the Microsoft Surface as a light, long lasting consumer consumption device, whereas the Surface Pro is a powerful, mobile content creation device and netbook equivalent. What's up with Cinder and DirectX? Cinder is a cross platform framework for C++ design engineering. In order to run and Apple, Android and Windows devices prior to Windows 8, the rendering libraries leveraged OpenGL as the open source, cross platform solution. Even though DirectX has been Microsoft's preferred rendering solution for advanced graphics programming, Windows traditionally provided both DirectX and OpenGL support from the desktop. However, Windows 8 Store applications are now exclusively DirectX based, to maximize reusability across the entire domain of Microsoft experiences including Windows Phone, Windows RT, Windows 8, and gaming. This means that Cinder apps that leverage OpenGL for their rendering will not work as Windows Store apps. To get a Cinder project running as a Windows Store app, the Cinder project needs to leverage a DirectX render instead of the default OpenGL renderer. Both OpenGL and DirectX have undergone significant changes over the years, with DirectX migrating away from the simpler fixed function pipeline of OpenGL early on. As hardware and software continue to advance, both libraries continue to progress in their own distinct ways. Windows 8 Store apps leverage the most recent version of DirectX 11.1, which itself has some breaking changes from DirectX 11, most notably is the loss of D3DX, a very popular helper library. As this document targets using Cinder for Windows Store apps, we will be using DirectX 11.1. Whereas you could have a DirectX renderer for desktop based Cinder experiences, because of the history and community support behind the existing OpenGL render, it would be a difficult choice to argue. However, to create a Windows Store app, DirectX 11.1 must be used as the underlying rendering technology in the Cinder framework. What about Visual Studio? Previous versions of Cinder were written to make it easy to use for Visual Studio 2010, and targeted Win32 applications. Since Windows Store apps require targeting the WinRT architecture, this has changed. To develop software for Window Store 8, you need to use Visual Studio 2012. We will be walking through the setup assuming you have downloaded the free version of the software, Visual Studio Express 2012. You should know, however ,that the professional versions of Visual Studio 2012 comes with several new features for professional graphics engineering, including a robust graphics debugger, DirectX support, visual shader editors, and tools for working with virtual models and objects. Enough theory, lets get started To create Windows Store apps, you need to have Windows 8 installed and running at least Visual Studio Express 2012 for Windows 8. Do not download Visual Studio Express 2012 for Web, Phone or Desktop. We are targeting Windows 8 here. Setting up Visual Studio Express 2012 for Windows 8 Once you have a copy of Windows 8 running natively or on a virtual machine from another Operating System, you can get the bytes for Visual Express 2012 for Windows here: http://www.microsoft.com/visualstudio/eng/products/visual-studio-express-products   Generic Episode Image                         When the installer has finished and you launch the application, you will be taken to a registration screen. If you choose not to register, Visual Studio Express 2012 will expire after 30 days. Go ahead and register the product.   Generic Episode Image   Once registration is complete, Visual Studio will launch for the first time. In order to create a Windows Store app, you need to setup a Developer license. A developer license allows you to develop, install and test apps on your computer before submitting them to the Microsoft store for publishing and deployment to the community. At this time, it would also be a good idea to go to the menu item Tools > Extensions and Updates and check for any updates to Visual Studio as well:   Generic Episode Image   Grabbing the Git branch Now that we have Windows 8 and Visual Studio Express 2012 setup, our next step is getting the correct Cinder bits on our machine. Since this is still under development, we need to pull from the correct developer branch of Cinder from Cinder's GitHub account. The professional version of Visual Studio 2012 allows for rich Git integration, but the free Express version doesn't support this, so you will need to have a standalone Git client if you choose to use the Express version of Visual Studio. If so, we recommend downloading the GitHub client, which installs both itself and helpful Git utilities. You can download the GitHub client here: https://help.github.com/articles/set-up-git   Generic Episode Image   After the GitHub client is installed, you may find it helpful to enter or setup your account. However, you should be able to pull the project if you just want to get up and running quickly using the Git Shell as explained further below. As a community developed, open source project, Cinder separates the stable, official version of its Cinder framework from newer branches that developers setup as they program future functionality. WinRT support for Cinder is currently being developed off of one of these feature branches, with the goal of integrating in to a future iteration of the master project. So we will need to clone the Cinder project locally, which defaults to the master branch, and then explicitly move to the dx_rt branch to get to the version under development that also includes support for Windows Store 8 projects. To clone Cinder, either open your Git enabled Power Shell in the directory you want to use and type: git clone https://github.com/cinder/Cinder.git   Or open a browser and go to the Cinder project page on GitHub.com. There you will see a Clone In Windows button that should launch the GitHub client automatically and start the local cloning process: https://github.com/cinder/Cinder/tree/dx_rt    Generic Episode Image   This should take several minutes to download the Cinder project and open it in your GitHub client. Once it appears as a line item in your GitHub client, you can right click the repository icon and select open a shell here. We will do the rest of the commands from the Power Shell directly.   If you look at your command prompt and you are still on the master branch, you can switch to the dx_rt branch by typing the following: git checkout dx_rt Or if you prefer to use the GitHub client you installed, you can switch from the master branch to the dx_rt branch from there as well. Generic Episode Image  If you are using the GitHub client, though, it would probably be a good idea to switch to a command shell for the next steps. You can do that from the client directly by right clicking on project's list item like so:   Generic Episode Image   The master, dev and dx_rt branches all require you to also install certain Boost libraries to the Cinder project directory before you can compile the Cinder framework. However, on the dx_rt branch we will be using, this process has been greatly automated for you. So once you've switched to the dx_rt branch, type in the following two commands to download the required Boost libraries that are compatible with this particular branch of Cinder for Windows Store: git submodule init git submodule update This may take a few minutes, but once it is done you should be ready to open the Cinder project and compile it for use.   Compiling Cinder for Windows Store apps Once you have pulled the Cinder project from its GitHub repository, switched to the dx_rt branch that contains the bits for working on Windows Store apps, and run the submodules that download the additional Boost dependencies, you are ready to open up the Cinder solution to compile the library.   Generic Episode Image     Go to where GitHub cloned the Cinder project, the default is Libraries\Documents\GitHub\Cinder. There you will find multiple version of the Cinder framework separated by development environment. You should see the xcode and vc10 solutions, but you will also three additional folders. Vc11 provides support for compiling Cinder for Visual Studio 2012, but still using OpenGL and thus limited to Desktop mode. VC11-DirectX is provides support for compiling Cinder for Visual Studio 2012 using DirectX 11 but also for Desktop mode. We will be focusing on the third option, the winrt folder. This is the solution that supports Windows Store apps and development. Launch Cinder/winrt/cinder.sln and the Cinder project should open up in Visual Studio 2012 automatically. If you are using the professional version of Visual Studio 2012, you can Batch Build all the versions you need. Since we are using the Express edition in this walkthrough, though, we will Build individually the debug and release versions of the Cinder library we need. We will build the debug version of the framework by making sure that our Solution Configuration in the toolbar is set to Debug and the Solution Platform is set to Win32.   Generic Episode Image   To build the solution, simply go to the Build menu option and select Build Solution. Generic Episode Image    Some warnings may pop up, but there should be no errors. Once that is done, you will find a new file in the Cinder project directory under: ..\Cinder\lib\winrt\Win32\Debug\cinder.lib This is the Cinder library your Windows Store projects will link to when you are programming and debugging your application. Now we need to rebuild this framework to provide a release version of this same framework. Going back to the Cinder project, and on the toolbar change the Solution Configuration option from Debug to Release and Build the solution again. You now have a Debug and Release version of the Cinder framework and are ready to start creating Windows Store programs against it for any Windows 8 device, including the Surface Pro. However, any WindowsRT device, such as the non-Pro version of Surface, will be running on ARM and so you would need to follow the above steps targeting the ARM platform instead of just the Win32 platform. Testing out the Library At this point, you are ready to explore the collection of DirectX samples created specifically for Windows Store apps. You can find various projects for Windows Store in the DirectX folder inside the samples folder. For our initial test, we will open the following sample: ..\Cinder\samples\DirectX\_winrtBasic\winrt\winrtBasic.sln When you open the solution in Visual Studio Express 2012, you will find basicApp.cpp in the Solution Explorer. This contains all the code we need to start using the Cinder framework.   Generic Episode Image   The code in this sample illustrates a few basic tasks, including loading an image from the assets folder and using it as a texture, loading fonts and displaying them on the screen, handling mouse events, drawing various geometries and implementing a basic follower easing algorithm in the update() call. Once you're looked over the code, you can press F5 or the Play button on the main toolbar to run the program on the machine. If you compiled both the Debug and Release versions of the framework, you can select either Solution Configuration. You will find a significant increase in speed in Release mode over Debug mode.   Generic Episode Image   You will also notice that the program has automatically installed its own Live Tile on your Start Screen, which you can use to launch the program again whenever you wish.   Generic Episode Image    Congratulations! You should now be ready to start exploring Cinder for Windows Store apps.   @rickbarraza   You can learn more about this branch by going to the Cinder forums found here: https://forum.libcinder.org/#Topic/23286000001540037     ]]> https://channel9.msdn.com/coding4fun/articles/Getting-started-with-Cinder-for-Windows-Store-Apps What is different on Windows 8Legacy software written for Windows 7 and prior targeted the traditional Windows API, often referred to as Win32. They resulting apps would be a combination of an executable, assets and libraries. The Windows 8 operating system introduces a new type of application, called a Windows Store app. The new architecture is called Windows Runtime, or WinRT for short. Windows Store apps are written exclusively against this new WinRT architecture. Windows 7 and prior only had one mode of interacting with software, launching the application's executable from the desktop or file path. Windows 8 now defaults to a Windows Runtime start screen, where Windows Store apps are presented and can be accessed through their respective Live Tiles. An application's Live Tile is registered automatically when that app is installed from the Windows Store. If a user needs to access legacy software that hasn't been migrated to the new Windows Store format, they can still get to the desktop from the Start Screen. Windows desktops and laptops have traditionally run on Intel processors, referred to frequently as x86 or x64 machines. However, in parallel with the release of Windows 8, an optimized version of the operating system designed for mobile ARM based devices was released called Windows RT. Windows RT devices, however, will not run legacy Win32 software, nor can you develop Win32 software for content. So unlike a Windows 8 computer, which is optimized for the Windows Store apps written against WinRT but still provides access to Win32 software from the desktop, Windows RT devices do not. What about the Microsoft Surface?There are two versions of the Microsoft Surface. The first version runs the Windows RT operating system and uses an ARM CPU. The Surface Pro, however, is an x64 device and runs Windows Pro 8. Both devices are optimized for Windows Store apps, but the Surface Pro is a fully featured computer as well, allowing you to install Visual Studio, Photoshop, https://channel9.msdn.com/coding4fun/articles/Getting-started-with-Cinder-for-Windows-Store-Apps Tue, 14 May 2013 22:20:52 GMT https://channel9.msdn.com/coding4fun/articles/Getting-started-with-Cinder-for-Windows-Store-Apps Rick Barraza Rick Barraza 9 https://channel9.msdn.com/coding4fun/articles/Getting-started-with-Cinder-for-Windows-Store-Apps/RSS MissionControl - A Flexible API for Remote Device Control In a race to optimize everything, developers often go to extremes to build software that performs routine tasks. MissionControl is a system that allows users to program a control center that stores interfaces with attached hardware sensors, allowing the users to control any other devices that can be activated via the underlying protocol. For demo purposes, the MissionControl build at this point is compatible with the Phidgets IR hybrid sensor. The system has two core components: • A server application, which is a Win32 console application that handles incoming queries and returns data to the connected clients. This application runs on the desktop machine with the connected sensor. • The Windows Phone application that sends requests to the target server and can trigger a variety of pre-programmed commands. The Basics Hardware and Communication Infrastructure One of the most important parts of the project is the signal capture and replication hardware. For the purposes of this project, I decided to use a dual-mode Phidgets IR sensor. It supports both IR code capture and subsequent replication. From a user’s perspective, this device also eliminates a substantial code-learning overhead as well as the potential error rate. Instead of searching for a device-specific hexadecimal sequence that later has to be transformed in a working IR code, the user simply has to point his remote control at the sensor and press the button that he wants accessible from a mobile device. Given that the capturing software is running on the target machine, once the sensor detects that a code can be repeated within an acceptable precision range, it will be automatically captured and stored, with all required transformations worked out in the backend using the free Phidgets SDK. clip_image002 Even though I can, I don’t have to handle the binary code content received through the sensor—the Phidgets .NET libraries carry built-in types that contain all the processed metadata that I will discuss later in this article. This sensor is connected through a USB port to a machine that acts as a communication gateway. This server should have port 6169 open for inbound connections. NOTE: The port number can be changed, but you have to keep it consistent between your server and client applications. The communication between the phone and the computer running the client is performed via a TCP channel—sockets are used to perform the initial connections and serialized data transfer. You can see the generalized data flow between the devices that are involved in the procedure in the graphic below: clip_image004 The server (desktop client) handles the local storage and release of all incoming IR codes. The mobile client has to know the location of the server—once specified and confirmed, it can send one of the pre-defined commands to it and either query the server for existing command groups (sets) or invoke one of the stored IR codes. When I pass data between devices, I use JSON for the serializable components. The data is also processed before being sent in order to speed-up the process—for example, on the server side the sets are serialized together with the associated codes. Like this: [ { "Name":"batman", "IsList":false, "Commands":[ { "Name":"test command", "Code":{ "Mask":{ "BitSize":12, "CodeData":"AAA=" }, "BitSize":12, "Encoding":2, "CarrierFrequency":38000, "DutyCycle":50, "Gap":44761, "Header":[ 2374, 606 ], "CodeData":"DJA=", "MinRepeat":5, "One":[ 1189, 606 ], "Repeat":null, "Trail":0, "Zero":[ 582, 606 ] } }, { "Name":"turn off", "Code":{ "Mask":{ "BitSize":12, "CodeData":"AAA=" }, "BitSize":12, "Encoding":2, "CarrierFrequency":38000, "DutyCycle":50, "Gap":44770, "Header":[ 2360, 613 ], "CodeData":"DJA=", "MinRepeat":5, "One":[ 1169, 613 ], "Repeat":null, "Trail":0, "Zero":[ 585, 613 ] } } ] } ] The inherent problem with the JSON data above is the fact that the phone client does not need the information related to the code binary sequence and all the metadata that goes with it. So it is effectively stripped down and reduced to the names of the sets (when a list of sets is requested) and commands (when a list of commands is requested). The Data Model As you saw from the description above, the server organizes individual infrared codes in sets. A single set is a bundle of codes that may or may not be related to each other—ultimately, this is the user’s decision. A good example of using sets is organizing IR commands by rooms, devices or code types. Each set has a unique name on the server, therefore eliminating the possibility of a request conflict. Each set stores individual commands built around the Command model: namespace Coding4Fun.MissionControl.API.Models { public class Command { public Command() { } public string Name { get; set; } public SerializableIRCode Code { get; set; } } } Despite the obvious Name property, you can see that I am using a SerializableIRCode instance that is specific to each model. Before going any further, I need to mention that the Phidgets SDK offers the IRLearnedCode model to store code contents. I could have used it instead, but there is an issue that prevents me from doing that—there is no public constructor defined for IRLearnedCode, therefore there is no way to serialize it, either with the built-in .NET serialization capabilities or JSON.NET, which I am using in the context of the project. Instead, I have this: using Phidgets; namespace Coding4Fun.MissionControl.API.Models { public class SerializableIRCode { public SerializableIRCode() { } IRLearnedCode code; public ToggleMask Mask { get; set; } public int BitSize { get; set; } public Phidgets.IRCodeInfo.IREncoding Encoding { get; set; } public int CarrierFrequency { get; set; } public int DutyCycle { get; set; } public int Gap { get; set; } public int[] Header { get; set; } public byte[] CodeData { get; set; } public int MinRepeat { get; set; } public int[] One { get; set; } public int[] Repeat { get; set; } public int Trail { get; set; } public int[] Zero { get; set; } } } It is an almost identical 1:1 copy of the original class, storing both the layout of the IR code and additional information related to its replication mechanism. You can learn more about each property listed in the model above by reading the official document on the topic. ToggleMask, the identity bit carrier that helps marking the code as repeated or not, is also implemented through a built-in Phidgets SDK model, and it has the same problem as IRLearnedCode. I implemented this model to replace it in the serializable code: namespace Coding4Fun.MissionControl.API.Models { public class ToggleMask { public ToggleMask() { } public int BitSize { get; set; } public byte[] CodeData { get; set; } } } I also needed an easy way to store all sets at once and carry all associated codes in a single instance retrieved from the storage. Here is the Set class: namespace Coding4Fun.MissionControl.API.Models { public class Set { public Set() { Commands = new List<Command>(); } public string Name { get; set; } public bool IsList { get; set; } public List<Command> Commands { get; set; } } } Notice that there is an IsList flag that allows me to specify how to display this specific list on the connecting device. This adds some level of flexibility for situations where the user wants to build a virtual remote for closely-related keys, such as digits. With that in mind, displaying those as a list might be inconvenient, wasting visual space on the client. But if the flag is set to false, the list can be displayed as a pad. Also, when the server performs the data exchange, it provides a single “envelope” that allows the connecting device to easily understand what the server is trying to do: namespace Coding4Fun.MissionControl.API.Models { public class ServerResponse { public string Identifier { get; set; } public string Marker { get; set; } public string Content { get; set; } } } The Identifier property carries the server IP address. That way, when a device receives a response, it is able to either accept it, because it knows that a response is requested from a target location, or discard it because the user is no longer using the specific server. Marker carries the command type of the sent command, therefore giving the Windows Phone application a hint as to what to do with the data. The server can send the following commands: • SET_LIST – returns the list of sets that are currently available on the server. • SET_COMMANDS:SET_NAME:IS_LIST – returns the list of commands that are associated with a given set that is currently stored on the server. • NOTIFICATION – send a simple notification to the client; no further action is required. Last but not least, Content is used to push the necessary data that is associated with the given Marker. It can be either a JSON-based string that lists the sets or commands, or a plain-text message that is used as an alert for the end-user. Server Architecture The server is the only component of this entire system that does all the heavy lifting. It learns commands, stores them and then generates new IR signal requests, as controlled from any of the connected clients. Let’s take a closer look at what happens behind the scenes—to start, I am going to document the network infrastructure. The Network Layer In order to be a reliable system, the server needs to be always ready to accept an incoming connection. For that purpose, it is possible to use the TcpListener class—an “always on” receiver that can handle incoming TCP connections. I integrated it in my CoreStarter class that is used to start the listener when the application is launched: namespace Coding4Fun.MissionControl.API { public class CoreStarter { static TcpListener listener; public static void LaunchSocket() { Console.WriteLine("Starting socket server on port {0}...", Constants.DEFAULT_PORT); listener = new TcpListener(NetworkHelper.GetLocalIPAddress(), Constants.DEFAULT_PORT); listener.Start(); for (int i = 0; i < Constants.MAX_CONCURRENT_CLIENTS; i++) { Thread socketThread = new Thread(new ThreadStart(ListenForData)); socketThread.Start(); } } private static void ListenForData() { Console.WriteLine("Listener thread started."); while (true) { Socket acceptedSocket = listener.AcceptSocket(); using (MemoryStream coreStream = new MemoryStream()) { try { Console.WriteLine("Incoming connection: {0}", acceptedSocket.RemoteEndPoint); using (Stream sourceStream = new NetworkStream(acceptedSocket)) { sourceStream.ReadTimeout = Constants.SOCKET_READ_TIMEOUT; byte[] buffer = new byte[Constants.DEFAULT_BUFFER_SIZE]; int i; while ((i = sourceStream.Read(buffer, 0, buffer.Length)) != 0) { coreStream.Write(buffer, 0, i); } } } catch { string data = Encoding.ASCII.GetString(coreStream.ToArray()); CommandHelper.InterpretCommand(data, acceptedSocket.RemoteEndPoint.ToString()); } } } } } } When LaunchSocket is called, the listener is activated on the current machine. As I mentioned above, the port number can be arbitrarily assigned, but has to be consistent between connecting apps in order for the TCP links to be established. Because I expect that more than one device will be connecting to the service at a time, the listener is set as active across a constant number of threads. NOTE: By default, a there is a maximum limit of 5 simultaneous clients. Although this number can be adjusted, be aware of the requirements of each environment in which a limited number of potential devices can connect. Even though the performance footprint of each thread is minimal, it can have a negative effect if used in unnecessarily large instances. ListenForData is used to read the incoming stream. When an inbound connection is accepted, the data is read with the help of a fixed content buffer. Then a read timeout is specified to prevent situations where the stream was completely read but the application still waits to pull non-existent data. Once the timeout milestone is hit, an exception is thrown, which marks the end of the stream—at this point, the plain text data that was received (remember that both the server and client exchange text data only) is passed to the command interpreter—CommandHelper, with a reference to the source of the command. The commands from the device are passed as serialized key-value pairs (KeyValuePair<T, T>), the key being the command with any possible suffixes, and the value being the contents of the command itself that helps the server identify the specific item in the local storage. InterpretCommand,in this case, does three things sequentially: 1. Deserialize the incoming string and create a KeyValuePair<string,string> instance. 2. Process the command and check whether it is recognizable. 3. Send a response to the client, if deemed necessary by the command type. The serialization and deserialization is done via JSON.NET. You can install this package in your console managed Win32 project and the Windows Phone application project via NuGet: clip_image005 The deserialization step is as simple as one line of C# code: KeyValuePair<string, string> result = JsonConvert.DeserializeObject<KeyValuePair<string, string>>(rawCommand.Remove(0, rawCommand.IndexOf('{'))); The string is sanitized to ensure that only JSON content is being passed to the serializer. Because of a relatively limited command set, I can put together the entire interpretation stack like this: // Get the initial list of sets on the target server if (result.Key == Constants.COMMAND_INIT) { SendSets(sourceLocation); } // Create a new set on the target server else if (result.Key.Contains(Constants.COMMAND_CREATE_SET)) { CreateSet(result, sourceLocation); SendSets(sourceLocation); } // Get the commands that are associated with a given set. else if (result.Key == Constants.COMMAND_GET_COMMANDS) { SendCommands(result.Value, sourceLocation); } // The client requested the server to learn a new command. else if (result.Key.Contains(Constants.COMMAND_LEARN_COMMAND)) { LearnCommand(result, sourceLocation); } // The client requested one of the commands to be executed on the // target server. else if (result.Key.Contains(Constants.COMMAND_EXECUTE)) { ExecuteCommand(result); } // The client has requested a set to be deleted from the target server. else if (result.Key == Constants.COMMAND_DELETE_SET) { DeleteSet(result.Value); SendSets(sourceLocation); } // The client has requested a set to be deleted from the target server. else if (result.Key.Contains(Constants.COMMAND_DELETE_COMMAND)) { DeleteCommand(result); SendCommands(result.Key.Split(new char[] { ':' })[1], sourceLocation); } All commands are constants, declared in the local helper class: public const string COMMAND_INIT = "INIT"; public const string COMMAND_CREATE_SET = "CREATE_SET"; public const string COMMAND_GET_COMMANDS = "GET_COMMANDS"; public const string COMMAND_LEARN_COMMAND = "LEARN_COMMAND"; public const string COMMAND_EXECUTE = "EXECUTE"; public const string COMMAND_DELETE_SET = "DELETE_SET"; public const string COMMAND_DELETE_COMMAND = "DELETE_COMMAND"; Notice that these are not the commands that the server sends back, but rather the commands it receives from connecting Windows Phone devices. Let’s now take a look at the breakdown for each command. SendSets: /// <summary> /// Send the list of sets to the client that requested those. /// </summary> /// <param name="sourceLocation">The location of the requesting client.</param> private static void SendSets(string sourceLocation) { Console.WriteLine("Received an initial set query from {0}", sourceLocation); ServerResponse response = new ServerResponse(); response.Marker = "SET_LIST"; response.Content = JsonConvert.SerializeObject(StorageHelper.GetRawSetNames()); response.Identifier = NetworkHelper.GetLocalIPAddress().ToString(); NetworkHelper.SendData(sourceLocation, JsonConvert.SerializeObject(response)); Console.WriteLine("Sent the set list to {0}", sourceLocation); } When this command is received, the server does not have to do much processing. It is only invoked when the client establishes the initiating link and needs to know what possible sets it can get from the target machine. The request is logged in the console and a server response is prepared that contains a serialized list of set names, which is later serialized as well and sent back to the source machine location. StorageHelper and NetworkHelper will be documented later in this article. CreateSet: /// <summary> /// Create a new set and store it on the local server. /// </summary> /// <param name="result">The original deserialized command.</param> /// <param name="sourceLocation">The location of the requesting client.</param> private static void CreateSet(KeyValuePair<string,string> result, string sourceLocation) { bool isSuccessful = false; string[] data = result.Key.Split(new char[] { ':' }); Console.WriteLine("There is an attempt to create the {0} set from {1}.", result.Value, sourceLocation); if (data[1].ToLower() == "list") isSuccessful = StorageHelper.AddSet(result.Value); else isSuccessful = StorageHelper.AddSet(result.Value, false); if (isSuccessful) Console.WriteLine("The {0} set was successfully created.", result.Value); else Console.WriteLine("Something happened and the {0} set was not created.", result.Value); } When a mobile device attempts to create a new set on the server, it sends a command in the following format: CREATE_SET:list/pad, SET_NAME CreateSet will get the type of the set that was created, will check whether a set with the same name already exists and will either create it or ignore the command altogether. No notification is sent to the connecting device, but either the failure or the success of the command is registered in the local console. SendCommands: /// <summary> /// Send a list of commands that are associated with the pushed set. /// </summary> /// <param name="setName">The original deserialized command.</param> /// <param name="sourceLocation">The location of the requesting client.</param> private static void SendCommands(string setName, string sourceLocation) { Console.WriteLine("There was a request to get the commands for the {0} set from {1}.", setName, sourceLocation); bool isList = StorageHelper.IsSetAList(setName); ServerResponse response = new ServerResponse(); response.Marker = string.Format("SET_COMMANDS:{0}:{1}", setName, isList); response.Identifier = NetworkHelper.GetLocalIPAddress().ToString(); response.Content = JsonConvert.SerializeObject(StorageHelper.GetRawCommandNames(setName)); NetworkHelper.SendData(sourceLocation, JsonConvert.SerializeObject(response)); Console.WriteLine("Command list for the {0} set were sent to {1}.", setName, sourceLocation); } Commands are sent in the same manner as sets—once the set is recognized, the names of the associated commands are retrieved and serialized inside a ServerResponse instance and then pushed back to the requesting device. LearnCommand: /// <summary> /// Learn a new command and store it on the target server. /// </summary> /// <param name="result">The original deserialized command.</param> /// <param name="sourceLocation">The location of the requesting client.</param> private static void LearnCommand(KeyValuePair<string,string> result, string sourceLocation) { Console.WriteLine("[!] Server in COMMAND LEARNING MODE! Point the remote towards the sensor and send a command."); string[] data = result.Key.Split(new char[] { ':' }); var set = StorageHelper.GetSingleSet(StorageHelper.GetSets(), data[1]); if (set != null) { if ((from c in set.Commands where c.Name == result.Value select c).FirstOrDefault() != null) { Console.WriteLine("Cannot learn command {0} for the following set: {1}. Command already exists.", data[1], result.Value); ServerResponse response = new ServerResponse(); response.Marker = "NOTIFICATION"; response.Identifier = NetworkHelper.GetLocalIPAddress().ToString(); response.Content = "We could not save the following command - " + result.Value + ". It already exists in the set."; NetworkHelper.SendData(sourceLocation, JsonConvert.SerializeObject(response)); } else { if (sensor == null) sensor = new IR(); sensor.open(-1); sensor.waitForAttachment(); sensor.Learn += (sender, args) => { Console.WriteLine("[!] Server learned the command and is no longer in COMMAND LEARNING MODE."); IRLearnedCode code = args.LearnedCode; code.CodeInfo.MinRepeat = 5; Command command = new Command(); command.Name = result.Value; command.Code = IRCodeWorker.GetSerializableIRCode(code); StorageHelper.AddCommand(command, set.Name); ServerResponse response = new ServerResponse(); response.Marker = "NOTIFICATION"; response.Identifier = NetworkHelper.GetLocalIPAddress().ToString(); response.Content = "The following command has been stored: " + result.Value; NetworkHelper.SendData(sourceLocation, JsonConvert.SerializeObject(response)); }; } } } Once a request was received that the server needs to learn a new command, an initial verification is done to make sure that the requested command name and set are not already taken. If neither the command nor the set exist, both will be created. After the basic setup is complete, the IR sensor is activated and will be waiting for the command to be learned. The way it works is quite simple – the sensor will remain in learning mode until the point where it recognizes a command without error, being 100% sure that it can be reproduced internally. You will need to point your remote towards the sensor and hold the button you want captured for one or two seconds in order for the command to be learned. NOTE: To ensure that a proper transmission is done, I manually set the minimal repeat value to 5. This is the number of times the sensor will fire the same code towards the target. That is the optimal value for a target device to receive the code if the remote is pointed directly at it without necessarily triggering the same command twice or more. After the command is learned, the code is processed and transformed into a serializable instance. The connecting client is then notified about whether the command was learned. ExecuteCommand: /// <summary> /// Execute one of the commands currently stored on the local server. /// </summary> /// <param name="result">The original deserialized command.</param> private static void ExecuteCommand(KeyValuePair<string,string> result) { string[] data = result.Key.Split(new char[] { ':' }); var set = StorageHelper.GetSingleSet(StorageHelper.GetSets(), data[1]); if (set != null) { var command = StorageHelper.GetSingleCommand(StorageHelper.GetCommands(set.Name), result.Value); IRLearnedCode code = IRCodeWorker.GetLearnedCode(command.Code); if (sensor == null) sensor = new IR(); sensor.open(-1); sensor.waitForAttachment(); sensor.transmit(code.Code, code.CodeInfo); sensor.close(); } } Command execution relies on the hardware sensor. The phone sends a command execution request in the following format: EXECUTE:SET_NAME, COMMAND_NAME Once the command is parsed out and found in the local storage, the IR code is transformed back to a model that is recognizable by the Phidgets SDK and transmitted towards the location where the sensor is pointed at the time of the execution. DeleteSet: /// <summary> /// Delete a single set and all the associated commands /// </summary> /// <param name="target">The name of the set.</param> private static void DeleteSet(string target) { var sets = StorageHelper.GetSets(); var targetSet = StorageHelper.GetSingleSet(sets, target); if (targetSet != null) { StorageHelper.RemoveSet(sets, targetSet); } } When deleting a set, only the name of the set should be specified. The user will get a warning on the client side that requires a confirmation of the deletion. The server will blindly execute the command. DeleteCommand: private static void DeleteCommand(KeyValuePair<string, string> result) { var sets = StorageHelper.GetSets(); string setName = result.Key.Split(new char[] {':'})[1]; var targetSet = StorageHelper.GetSingleSet(sets, setName); var command = (from c in targetSet.Commands where c.Name == result.Value select c).FirstOrDefault(); if (command != null) { targetSet.Commands.Remove(command); StorageHelper.SerializeSets(sets); } } Not only can the user remove entire sets, but he can also target specific commands from a given set. Once a DELETE_COMMAND directive is recognized, the set name is parsed out from the original string, that follows the DELETE_COMMAND:SET_NAME, COMMAND_NAME format, and a simple LINQ query extracts the command instance, removes it and stores the set content on the local hard drive. Notice that for some commands, particularly for set creation, deletion and command deletion, the server will return a list of the remaining items. The contents will be automatically updated on the devices, which will be waiting for that response. This measure was deliberately introduced to minimize the chances of a user triggering a command that was already deleted or trying to query a previously removed set. Transforming Codes You might have noticed that I am using IRCodeWorker.GetSerializableCodeType to transform a Phidgets SDK native IR code model into a serializable one. This is a helper function that performs a field copy of the existing object. Because of the differences in the model structure, it has to be done manually: public static SerializableIRCode GetSerializableIRCode(IRLearnedCode code) { SerializableIRCode sCode = new SerializableIRCode(); sCode.BitSize = code.Code.BitCount; sCode.Encoding = code.CodeInfo.Encoding; sCode.CarrierFrequency = code.CodeInfo.CarrierFrequency; sCode.CodeData = code.Code.Data; sCode.DutyCycle = code.CodeInfo.DutyCycle; sCode.Gap = code.CodeInfo.Gap; sCode.Header = code.CodeInfo.Header; sCode.MinRepeat = 5; sCode.One = code.CodeInfo.One; sCode.Repeat = code.CodeInfo.Repeat; sCode.Trail = code.CodeInfo.Trail; sCode.Zero = code.CodeInfo.Zero; sCode.Mask = new ToggleMask() { BitSize = code.CodeInfo.ToggleMask.BitCount, CodeData = code.CodeInfo.ToggleMask.Data }; return sCode; } The reverse process is easier because I can pass each of the existing properties to the IRCodeInfo constructor. The only difference is the fact that I need to use Reflection to create an instance of IRLearnedCode because there is no public constructor defined and a dynamic object has to be created: internal static IRLearnedCode GetLearnedCode(SerializableIRCode serializableIRCode) { IRCode code = new IRCode(serializableIRCode.CodeData, serializableIRCode.BitSize); IRCodeInfo info = new IRCodeInfo(serializableIRCode.Encoding, serializableIRCode.BitSize, serializableIRCode.Header, serializableIRCode.Zero, serializableIRCode.One, serializableIRCode.Trail, serializableIRCode.Gap, serializableIRCode.Repeat, serializableIRCode.MinRepeat, serializableIRCode.Mask.CodeData, IRCodeInfo.IRCodeLength.Constant, serializableIRCode.CarrierFrequency, serializableIRCode.DutyCycle); object[] parameters = new object[] { code, info }; BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance; object instantType = Activator.CreateInstance(typeof(IRLearnedCode), flags, null, parameters, null); return (IRLearnedCode)instantType; } Command and Set Management Looking back at the code that I put together for the command interpreter, there is one class that does all local content manipulation—StorageHelper. This is a simple class that performs LINQ queries on set as well as command collections, and makes sure that all the changes are preserved in the sets.xml file in the application folder that is used as the only storage place for all the content that is being manipulated by the server. namespace Coding4Fun.MissionControl.API.Helpers { public class StorageHelper { /// <summary> /// Lists all available sets that are currently stored on the server. /// </summary> /// <returns>List of sets on the machine.</returns> internal static List<Set> GetSets() { List<Set> sets = null; string rawContent = GetRawSets(); sets = JsonConvert.DeserializeObject<List<Set>>(rawContent); return sets; } /// <summary> /// Returns the list of commands that are associated with the given set. /// </summary> /// <param name="setName">The name of the target set.</param> /// <returns>List of commands associated with the given set.</returns> internal static List<Command> GetCommands(string setName) { List<Command> commandList = null; var sets = GetSets(); Set singleSet = null; if (sets != null) singleSet = (from c in sets where c.Name == setName select c).FirstOrDefault(); if (singleSet != null) { commandList = singleSet.Commands; } return commandList; } /// <summary> /// Gets the list of names for the commands in the requested set. /// </summary> /// <param name="setName">The name of the target set.</param> /// <returns>List of commands associated with the given set.</returns> internal static List<string> GetRawCommandNames(string setName) { List<Command> commandList = GetCommands(setName); List<string> stringSet = null; if (commandList != null) { stringSet = commandList.Select(x => x.Name).ToList(); } return stringSet; } /// <summary> /// Get the list of names for all sets on the local server. /// </summary> /// <returns>List of sets on the machine.</returns> internal static List<string> GetRawSetNames() { List<Set> sets = GetSets(); List<string> stringSet = null; if (sets != null) { stringSet = sets.Select(x => x.Name).ToList(); } return stringSet; } /// <summary> /// Get the raw string contents of sets.xml. Should only be used in the /// context of this class. /// </summary> /// <returns>JSON string representing stored sets and commands.</returns> internal static string GetRawSets() { string sets = string.Empty; if (File.Exists("sets")) { using (StreamReader reader = new StreamReader(File.OpenRead("sets"))) { sets = reader.ReadToEnd(); } } else { FileStream stream = File.Create("sets.xml"); stream.Close(); } return sets; } /// <summary> /// Check whether a set is marked with a IsList flag. /// </summary> /// <param name="setName">The name of the target set.</param> /// <returns>TRUE - set is a list. FALSE - set is not a list.</returns> internal static bool IsSetAList(string setName) { bool isList = true; var sets = GetSets(); Set set = null; if (sets != null) set = (from c in sets where c.Name == setName select c).FirstOrDefault(); if (set != null) isList = set.IsList; return isList; } /// <summary> /// Serialize the set collection to sets.xml /// </summary> /// <param name="sets">Collection to be serialized.</param> /// <returns>true if sets are serialized.</returns> private static bool SerializeSets(List<Set> sets) { try { using (StreamWriter writer = new StreamWriter("sets.xml", false)) { string data = JsonConvert.SerializeObject(sets); writer.Write(data); } return true; } catch { return false; } } /// <summary> /// Add a new set to the existing global set collection. /// </summary> /// <param name="name">Set name.</param> /// <returns>true if successfully added set.</returns> internal static bool AddSet(string name, bool isList = true) { var sets = GetSets(); if (sets == null) sets = new List<Set>(); var singleSet = GetSingleSet(sets, name); if (singleSet == null) sets.Add(new Set { Name = name, IsList = isList }); if (SerializeSets(sets)) return true; else return false; } /// <summary> /// Retrieves a single set from a collection that has a specific name. /// </summary> /// <param name="sets">The source collection from which to extract the set.</param> /// <param name="name">The name of the set to get.</param> /// <returns>An instance of the found set, if any.</returns> internal static Set GetSingleSet(List<Set> sets, string name) { if (sets != null) return (from c in sets where c.Name == name select c).FirstOrDefault(); else return null; } /// <summary> /// Add a IR command to an existing set. If the set is not found, it will be created. /// </summary> /// <param name="command">The command instance to be added.</param> /// <param name="targetSet">The name of the target set.</param> /// <returns>true if the command was successfully added.</returns> internal static bool AddCommand(Command command, string targetSet) { var sets = GetSets(); if (sets == null) sets = new List<Set>(); var singleSet = GetSingleSet(sets, targetSet); if (singleSet == null) singleSet = new Set { Name = targetSet }; var singleCommand = (from c in singleSet.Commands where c.Name == command.Name select c).FirstOrDefault(); if (singleCommand == null) { singleSet.Commands.Add(command); if (SerializeSets(sets)) return true; else return false; } else return false; } /// <summary> /// Retrieve a single command instance from one of the sets on the local server. /// </summary> /// <param name="commands">Original list of commands.</param> /// <param name="name">Name of the command to be retrieved.</param> /// <returns>An instance of the command, if found. NULL if not.</returns> internal static Command GetSingleCommand(List<Command> commands, string name) { if (commands != null) return (from c in commands where c.Name == name select c).FirstOrDefault(); else return null; } /// <summary> /// Remove a set from a local machine. /// </summary> /// <param name="sets">Original list of sets.</param> /// <param name="targetSet">Name of the set to remove.</param> internal static void RemoveSet(List<Set> sets, Set targetSet) { sets.Remove(targetSet); SerializeSets(sets); } } } Sending Data Back to the Client SendData in the NetworkHelper class handles all outbound connections. Here is its structure: /// <summary> /// Send data to the target network machine. /// </summary> /// <param name="destination">The target machine IP.</param> /// <param name="data">Data to be sent, in string format.</param> /// <param name="sanitizeIp">Determines whether to remove the port from the given IP string.</param> public static void SendData(string destination, string data, bool sanitizeIp = true) { using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { string completeIp = string.Empty; if (sanitizeIp) completeIp = destination.Remove(destination.IndexOf(":"), destination.Length - destination.IndexOf(":")); client.Connect(completeIp, 6169); client.Send(Encoding.UTF8.GetBytes(data)); } } A new stream socket is created in order to connect to the target machine over the TCP pipe. If IP sanitization is enabled, the port is stripped from the address in order to pass a valid IP. A Socket instance cannot directly handle IPs of the format: 255.255.255.0:PORT_NUMBER Later, in a synchronous manner, a connection is established and the data is sent. At this point, you can see that the barebones service offers a flexible way to manage content. It can be accessed by any application type as long as the server can be accessed and the application can send commands in the pre-defined format and the content requested is actually located on the target server. This allows for high levels of extensibility and interoperability, as the server usage is not limited to a single platform. If I decide to create a Windows Store application that would allow me to control my TV, I simply need to add socket connection layer that will send plain strings to the machine where the IR sensor is connected. Similarly, if some functionality needs to be added, it is possible to do so without ever touching the client applications. A modification in the endpoint will be reflected with no direct effect on all connection applications as long as all handled returned and requested values are preserved. The only additional requirement is that if the client applications want to take advantage of newly introduced capabilities, they need to have an updated command transmission layer for the new command types. In Program.cs, I simply need to start the server through the CoreStarter class: namespace Coding4Fun.MissionControl.API { class Program { static void Main(string[] args) { Console.WriteLine("Coding4Fun MissionControl Server"); CoreStarter.LaunchSocket(); } } } clip_image007 Mobile client overview The mobile client does not have the capability to send commands directly to the IR sensor. Instead, it connects to a remote machine that has the IR sensor plugged in and attempts to invoke a command from the list returned by the service. A single mobile client can support control over multiple servers. NOTE: Make sure that at the time of working with the Windows Phone client, the server is actually running on your local machine. To make it easier to test, also open port 6169 for incoming connections in Windows Firewall. When building a Windows Phone application, make sure you have the proper version of the SDK installed, as well as a SLAT-compatible machine if you plan on testing the application in the emulator. Networking Infrastructure The Windows Phone application also relies on a network infrastructure somewhat similar to that of the server. There is a TCP listener that is created when the application is started: // Code to execute when the application is launching (eg, from Start) // This code will not execute when the application is reactivated private void Application_Launching(object sender, LaunchingEventArgs e) { ServiceSerializer.DeserializeServices(); listener.OnClientConnected += listener_OnClientConnected; listener.Start(6169); } Here, listener is an instance of TcpSocketListener—a custom class designed to handle incoming network connections: namespace Coding4Fun.MissionControl.WP.Network { public class TcpSocketListener : SocketConnectorBase { StreamSocketListener coreSocket; public async void Start(int port) { coreSocket = new StreamSocketListener(); coreSocket.ConnectionReceived += coreSocket_ConnectionReceived; try { await coreSocket.BindServiceNameAsync(port.ToString()); } catch (Exception ex) { Debug.WriteLine(ex.Message); coreSocket.Dispose(); coreSocket = null; OnConnectionCompleted(new ConnectionEventArgs { IsSuccessful = false, DeviceID = string.Empty }); } } async void coreSocket_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { Debug.WriteLine("Connection received!"); DataReader reader = new DataReader(args.Socket.InputStream); try { while (true) { StringBuilder builder = new StringBuilder(); uint actualLength = 1; while (actualLength > 0) { actualLength = await reader.LoadAsync(256); builder.Append(reader.ReadString(actualLength)); } OnConnectionCompleted(new ConnectionEventArgs { Socket = args.Socket, IsSuccessful = true, DeviceID = args.Socket.Information.RemoteHostName.DisplayName, Token = builder.ToString() }); break; } } catch (Exception exception) { Debug.WriteLine(exception.Message); OnConnectionCompleted(new ConnectionEventArgs { IsSuccessful = false }); } } } } A StreamSocketListener is used for the connection core. When a connection is received, a continuous loop reads the entire contents of the incoming stream. OnConnectionCompleted is declared in the base class—SocketConnectorBase. namespace Coding4Fun.MissionControl.WP.Network { public class SocketConnectorBase { public event EventHandler<ConnectionEventArgs> OnClientConnected; public virtual void OnConnectionCompleted(ConnectionEventArgs connectionArgs) { if (OnClientConnected != null) { OnClientConnected(this, connectionArgs); } } public event EventHandler<bool> OnSendCompletedEvent; public virtual void OnSendCompleted(bool succeeded) { if (OnSendCompletedEvent != null) { OnSendCompletedEvent(this, succeeded); } } } public class ConnectionEventArgs : EventArgs { public StreamSocket Socket { get; set; } public string DeviceID { get; set; } public string Token { get; set; } public bool IsSuccessful { get; set; } } } ConnectionEventArgs here is used to identify the content that is passed to the client. DeviceID gives access to the source IP, IsSuccessful tells the developer whether the established connection is active and the Token carries the raw string if any was received. Sending data is simplified to the maximum with the help of the SocketClient class, which relies on a StreamSocket instance that handles outbound connections and writing to the output stream: namespace Coding4Fun.MissionControl.WP.Network { public class SocketClient : SocketConnectorBase { StreamSocket _socket; public SocketClient() { _socket = new StreamSocket(); } public SocketClient(StreamSocket socket) { _socket = socket; } public async void Connect(string hostName, int portNumber) { try { await _socket.ConnectAsync(new HostName(hostName), portNumber.ToString(), SocketProtectionLevel.PlainSocket); OnConnectionCompleted(new ConnectionEventArgs { IsSuccessful = true }); } catch (Exception ex) { Debug.WriteLine(ex.Message); OnConnectionCompleted(new ConnectionEventArgs { IsSuccessful = false }); } } public async void Send(string dataToSend) { try { using (DataWriter writer = new DataWriter(_socket.OutputStream)) { // Write the length of the binary data that is being // sent to the client. writer.WriteUInt32((UInt32)dataToSend.Length); writer.WriteString(dataToSend); // Send the actual data. await writer.StoreAsync(); writer.DetachStream(); OnSendCompleted(true); } } catch { _socket.Dispose(); _socket = null; OnSendCompleted(false); } } } } As with the listener class, SocketClient supports OnConnectionCompleted to notify the application that the connection attempt completed. Back in App.xaml.cs, the data from the incoming connection captured by the TcpSocketListener instance is passed to the ResponseHelper class: void listener_OnClientConnected(object sender, ConnectionEventArgs e) { ResponseHelper.HandleIncomingResponse(e.Token); } This class reads the possible three commands sent by the server and interprets them, creating internal collections from the raw data if the current server IP matches the one obtained in the ServerResponse (the same model in the desktop application): using Coding4Fun.MissionControl.WP.Models; using Coding4Fun.MissionControl.WP.ViewModels; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Globalization; using System.Windows; namespace Coding4Fun.MissionControl.WP.Misc { public class ResponseHelper { public static void HandleIncomingResponse(string rawResponse) { if (rawResponse != null) { ServerResponse response = JsonConvert.DeserializeObject<ServerResponse>(rawResponse); if (response.Marker == Constants.COMMAND_SERVER_NOTIFICATION) { Deployment.Current.Dispatcher.BeginInvoke(() => { MessageBox.Show(response.Content, "Server Response", MessageBoxButton.OK); }); } else { if (CommonViewModel.Instance.IsWaiting) { if (response.Identifier == CommonViewModel.Instance.CurrentServer.Location) { // returns the list of sets that are associated with the current server. if (response.Marker == Constants.COMMAND_SERVER_SET_LIST) { List<string> items = JsonConvert.DeserializeObject<List<string>>(response.Content); if (items != null) { List<Group<string>> groupedItems = Group<string>.CreateGroups(items, CultureInfo.CurrentCulture, (string s) => { return s[0].ToString(); }, true); SetsPageViewModel.Instance.Sets = groupedItems; } else { SetsPageViewModel.Instance.Sets = new List<Group<string>>(); } Deployment.Current.Dispatcher.BeginInvoke(() => { CommonViewModel.Instance.IsWaiting = false; if (!App.RootFrame.CurrentSource.ToString().Contains("SetsPage")) { App.RootFrame.Navigate(new Uri("/Views/SetsPage.xaml", UriKind.Relative)); } }); } // returns the list of commands associated with a given set. else if (response.Marker.Contains(Constants.COMMAND_SERVER_SET_COMMANDS)) { string[] data = response.Marker.Split(new char[] { ':' }); if (data[1] == CommonViewModel.Instance.CurrentSet) { bool isList = false; bool.TryParse(data[2].ToLower(), out isList); if (isList) { CommonViewModel.Instance.CurrentSetType = "list"; } else { CommonViewModel.Instance.CurrentSetType = "pad"; } CommandsPageViewModel.Instance.Commands = new System.Collections.ObjectModel.ObservableCollection<string>(JsonConvert.DeserializeObject<List<string>>(response.Content)); Deployment.Current.Dispatcher.BeginInvoke(() => { CommonViewModel.Instance.IsWaiting = false; App.RootFrame.Navigate(new Uri("/Views/CommandsPage.xaml", UriKind.Relative)); }); } } } } } } } } } If the response comes from a server that is different than the one that is currently active, the data is discarded as the user no longer needs it. Also, for specific commands, the mobile application will be on standby, waiting for a response (unless the user decides to cancel the request) – the IsWaiting flag is an application-wide indicator that a pending server action is in the queue. Same as with the server, the commands in the Windows Phone application are represented through pre-defined constants: public const string COMMAND_SERVER_SET_LIST = "SET_LIST"; public const string COMMAND_SERVER_SET_COMMANDS = "SET_COMMANDS"; public const string COMMAND_SERVER_NOTIFICATION = "NOTIFICATION"; Let’s now take a closer look at how it is handled internally to build the visual layer. Handling the Data The first thing users will see when the application is launched is the list of registered servers: wp_ss_20130507_0003 This is ServiceListPage.xaml. The list of servers that were added is retrieved from the isolated storage on application startup, with the help of the standard serialization routine implemented in the Coding4Fun Toolkit—specifically, its storage subset (you can get it via NuGet): clip_image011 The one-liner that initializes the internal server collection is as follows: MainPageViewModel.Instance.Servers = Serialize.Open<ObservableCollection<Server>>(Constants.SERVERS_FILE);   Here, the SERVERS_FILE constant is equal to servers.xml. It is a good idea to use constants for file names in order to be able to later modify the location through a single change instead of digging through the many source files in a solution to find references to the old location. The user can define an unlimited number of servers, as long as he can access those. There is no restriction on the location of the server itself—it can work with the desktop in your room just as well as with a PC on the other end of the world (yes, this was tested). When adding a new server, the user is redirected to AddServicePage.xaml, where he can fill in connection details, as well as the location of an image that would help him identify that specific item in the general list: wp_ss_20130423_0005 Once data entry is complete, it is validated internally to make sure that the server is not already registered with the same name and location. If the validation step passes, the server is added to the list of local access points and the user is returned back to the server selection page: private void AttemptAddService() { if (!string.IsNullOrWhiteSpace(txtName.Text) && !string.IsNullOrWhiteSpace(txtLocation.Text)) { Server server = new Server { Name = txtName.Text, Location = txtLocation.Text, ImageURL = !string.IsNullOrWhiteSpace(txtAvatar.Text) ? txtAvatar.Text : string.Empty }; if (!CollectionHelper.CheckServerExists(server)) { MainPageViewModel.Instance.Servers.Add(server); Serialize.Save(Constants.SERVERS_FILE, MainPageViewModel.Instance.Servers); NavigationService.GoBack(); } else { Alert.Send("The service with this name or location is already registered."); } } else { Alert.Send("The service needs a name and a location."); } } When a server selection is made by the user, it is necessary to show SetsPage.xaml. However, it is necessary to also check whether the server is active or not prior to the actual navigation. With the help of internal bindings, I am doing it through a RelayCommand: public RelayCommand SelectServerCommand { get; private set; } private async void SelectServer(object server) { CommonViewModel.Instance.IsWaiting = true; CommonViewModel.Instance.CurrentServer = (Server)server; bool result = await CommonViewModel.Instance.CommandClient.SendCommand(CommonViewModel.Instance.CurrentServer.Location, Constants.COMMAND_SERVER_HELLO, string.Empty); if (!result) { Alert.Send(Constants.MESSAGE_SERVER_CONNECT_FAIL); CommonViewModel.Instance.CurrentServer = null; CommonViewModel.Instance.IsWaiting = false; } }   COMMAND_SERVER_HELLO represents the initial handshake command that I mentioned earlier—it requests the list of sets on the target server. To streamline command processing, CommandClient is used and wraps around the SocketClient class, giving me the possibility to call SendCommand with the command metadata without having to explicitly handle socket interactions in my views: namespace Coding4Fun.MissionControl.WP.Network { public class CommandClient { private SocketClient client; public Task<bool> SendCommand(string key, string value, Action<bool> onCompleted = null) { var taskCompletionSource = new TaskCompletionSource<bool>(); client = new SocketClient(); client.OnClientConnected += (s, args) => { if (args.IsSuccessful) { string data = JsonConvert.SerializeObject(new KeyValuePair<string, string>(key, value)); client.Send(data); } taskCompletionSource.SetResult(args.IsSuccessful); client = null; }; client.Connect(Binder.Instance.CurrentService.Location, 6169); return taskCompletionSource.Task; } } } From here on, ResponseHelper is once again involved, grouping all the data alphabetically—remember this call: // returns the list of sets that are associated with the current server. if (response.Marker == Constants.COMMAND_SERVER_SET_LIST) { List<string> items = JsonConvert.DeserializeObject<List<string>>(response.Content); if (items != null) { List<Group<string>> groupedItems = Group<string>.CreateGroups(items, CultureInfo.CurrentCulture, (string s) => { return s[0].ToString(); }, true); Binder.Instance.Sets = groupedItems; } else { Binder.Instance.Sets = new List<Group<string>>(); } }   The grouped collection is later bound to a LongListSelector instance: wp_ss_20130507_0001 For each handshake call to the server, the set collection will be re-initialized, in case the server was updated by another device while the user was not taking any actions. Adding a set takes the user to AddSetPage.xaml, where the user input is once again validated and the appropriate command sent to the currently selected server: private async void AttemptAddSet() { if (!string.IsNullOrWhiteSpace(txtName.Text)) { this.Focus(); bool commandSent = await CommonViewModel.Instance.CommandClient.SendCommand(CommonViewModel.Instance.CurrentServer.Location, string.Format(Constants.COMMAND_CREATE_SET, ((ListPickerItem)lstType.SelectedItem).Content.ToString()), txtName.Text); if (!commandSent) { Alert.Send(Constants.MESSAGE_SERVER_CONNECT_FAIL); } else { CommonViewModel.Instance.IsWaiting = true; NavigationService.GoBack(); } } else { Alert.Send(Constants.MESSAGE_NO_NAME_FAIL); } } wp_ss_20130430_0002 The end-user is also able to specify whether the new set is a list or a pad. Since the server does not explicitly define the type of a set beyond marking whether it’s a list, it is possible to have an arbitrary type here. To give you an idea of what it looks like in the current release of MissionControl, here is the pad representation of a set of commands: wp_ss_20130507_0002 It is a convenient way to display buttons for typical actions, such as channel switching through digits. Since we can safely assume many of those will be tapped sequentially, a list would be inconvenient to scroll through. On the other hand, some remote control commands work well with a list because no sequences are invoked most of the time: wp_ss_20130507_0004 If the pad is not desired, it can easily be swapped with another design and internal template - the appearance is swapped dynamically and is not hard-bound to a string value. Once a set is selected, a connection attempt is made to the current server in order to check whether there is still a communication channel available with the resource that fetched the initial list of commands. If a connection is established, the server will also return a set of commands that are available in the set at the time of the request. private async void AttemptLoadCommands() { bool commandSent = await CommonViewModel.Instance.CommandClient.SendCommand(CommonViewModel.Instance.CurrentServer.Location, Constants.COMMAND_GET_COMMANDS, CommonViewModel.Instance.CurrentSet); if (!commandSent) { Alert.Send(Constants.MESSAGE_SERVER_CONNECT_FAIL); CommonViewModel.Instance.IsWaiting = false; } } You’ve probably already noticed that both for commands and sets, the initial routine verifies the connection to the server. The server might go dark after the set list is loaded, therefore rendering any attempt to process other commands impossible. To avoid scenarios in which the user is waiting for a response from a server that doesn’t run, the user is notified before being redirected to the subsequent view, if the connection fails. That way unnecessary navigation passes are out of the picture. If the user selects a command from one of the lists demonstrated above, an EXECUTE directive is issued via the CommandClient class: private async void lstCommands_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (lstCommands.SelectedItem != null) { string selectedItem = lstCommands.SelectedItem.ToString(); CommandClient commandClient = new CommandClient(); bool commandSent = await commandClient.SendCommand(string.Format(Constants.COMMAND_EXECUTE, Binder.Instance.CurrentSet), selectedItem); if (!commandSent) { Alert.Send(Constants.MESSAGE_SERVER_CONNECT_FAIL); } lstCommands.SelectedItem = null; } } Once the server receives the command, it will send it to the target without additional notifications being released to the connecting client. When it comes to learning a new remote control code in LearnCodePage.xaml, the procedure is exactly the same as with any other part of the server communication process — a LEARN_CODE command is sent to the server with the associated set and new command name, and the server will wait for incoming IR input, leaving the connecting device free (no waiting lock is issued): private async void AttemptLearnCode() { if (!string.IsNullOrWhiteSpace(txtName.Text)) { CommonViewModel.Instance.IsWaiting = true; this.Focus(); bool commandSent = await CommonViewModel.Instance.CommandClient.SendCommand(CommonViewModel.Instance.CurrentServer.Location, string.Format(Constants.COMMAND_LEARN_NEW, CommonViewModel.Instance.CurrentSet), txtName.Text); if (!commandSent) { Alert.Send(Constants.MESSAGE_SERVER_CONNECT_FAIL); } else { Alert.Send(Constants.MESSAGE_COMMAND_LEARN_WAIT); NavigationService.GoBack(); } CommonViewModel.Instance.IsWaiting = false; } else { Alert.Send(Constants.MESSAGE_NO_NAME_FAIL); } } Once the server learns a new command — if, and only if, the user still works in the context of the same server — an alert will be displayed, telling the user whether the command was successfully learned. For convenience purposes, I also implemented a quick launch panel, where frequently-used commands can be placed. Whenever a user wants to add something here, he will tap-and-hold on an existing command in any of the sets that are available for any given server, and select the "add to quick launch" option. Once completed, the stored commands will be available on the main page, even when the user is not directly connected to the server that carries the command: wp_ss_20130507_0005 Because this interaction layer is placed outside the boundaries of a single server or set, I needed to create a special data model to store the quick commands and the related connection information, that would let me call the server even when it is not the currently selected one: namespace Coding4Fun.MissionControl.WP.Models { public class Favorite { public string CommandName { get; set; } public string ParentSet { get; set; } public string ServerLocation { get; set; } } } Same as with the list of servers, the list of favorites is deserialized on application startup: MainPageViewModel.Instance.Favorites = Serialize.Open<ObservableCollection<Favorite>>(Constants.FAVORITES_FILE);   Logically, we would also need to have a way to eliminate trailing commands for servers or sets that have been removed, since those can no longer be invoked or might have a different meaning on servers that were added and have the same IP as the previous owner. This is easily done with a simple LINQ expression that is passed to RemoveTrailingFavorites in the CollectionHelper class: internal static void RemoveTrailingFavorites(Func<Favorite,bool> predicate) { var favorites = MainPageViewModel.Instance.Favorites.Where(predicate).ToList(); if (favorites.Count() > 0) { foreach (var favorite in favorites) { Deployment.Current.Dispatcher.BeginInvoke(() => { MainPageViewModel.Instance.Favorites.Remove(favorite); }); } Serialize.Save(Constants.FAVORITES_FILE, MainPageViewModel.Instance.Favorites); } } A typical usage scenario is reflected in the server removal snippet: public static bool RemoveServer(Server server) { try { RemoveTrailingFavorites(x=> x.ServerLocation == server.Location); MainPageViewModel.Instance.Servers.Remove(server); Serialize.Save(Constants.SERVERS_FILE, MainPageViewModel.Instance.Servers); return true; } catch { return false; } } Because an ObservableCollection<T> is used for both the list of servers and quick launch commands, the view will be instantly updated to reflect the changes. Improvements to the project This specific project relies on a hybrid IR transmitter and receiver, which is not exactly cheap. As a step forward for this project, it can be adapted to use a central microcontroller that acts as a server (e.g. Netduino) and a series of IR emitters (instead of using a composite receiver/emitter) connected to it. Reduced cost for the IR infrastructure is key, as not every single component needs the capability to learn IR commands. You can have a single command capturing endpoint and multiple transmitters. This will also eliminate the need for a desktop client, since the server on the microcontroller can be built to be accessible via a web-browser. Another important aspect not covered in this article is security. With the current workflow, anyone who has direct access to the server IP is able to do anything he wants with the data handled by the server. I am basing my writing on the assumption that you are testing the application on a secure local network and that the the odds of something like this happening are close to zero. However, for other environments where tampering with a server might be unacceptable, consider implementing a layer of security between the server and the client. Conclusion With affordable microcontrollers and sensors, home and office automation can be a nice bonus resulting from little investment. This article covers the implementation of a proof-of-concept server and application that can be easily extended and adapted to a variety of environments and devices. ]]> https://channel9.msdn.com/coding4fun/articles/MissionControl-A-Flexible-API-for-Remote-Device-Control In a race to optimize everything, developers often go to extremes to build software that performs routine tasks. MissionControl is a system that allows users to program a control center that stores interfaces with attached hardware sensors, allowing the users to control any other devices that can be activated via the underlying protocol. For demo purposes, the MissionControl build at this point is compatible with the Phidgets IR hybrid sensor. The system has two core components: A server application, which is a Win32 console application that handles incoming queries and returns data to the connected clients. This application runs on the desktop machine with the connected sensor. The Windows Phone application that sends requests to the target server and can trigger a variety of pre-programmed commands. The BasicsHardware and Communication InfrastructureOne of the most important parts of the project is the signal capture and replication hardware. For the purposes of this project, I decided to use a dual-mode Phidgets IR sensor. It supports both IR code capture and subsequent replication. From a user’s perspective, this device also eliminates a substantial code-learning overhead as well as the potential error rate. Instead of searching for a device-specific hexadecimal sequence that later has to be transformed in a working IR code, the user simply has to point his remote control at the sensor and press the button that he wants accessible from a mobile device. Given that the capturing software is running on the target machine, once the sensor detects that a code can be repeated within an acceptable precision range, it will be automatically captured and stored, with all required transformations worked out in the backend using the free Phidgets SDK. Even though I can, I don’t have to handle the binary code content received through the sensor—the Phidgets .NET libraries carry built-in types that contain all the processed metadata that I will discuss later in this article. 229 https://channel9.msdn.com/coding4fun/articles/MissionControl-A-Flexible-API-for-Remote-Device-Control Mon, 13 May 2013 15:12:48 GMT https://channel9.msdn.com/coding4fun/articles/MissionControl-A-Flexible-API-for-Remote-Device-Control Clint Rutkas, Den Delimarsky Clint Rutkas, Den Delimarsky 5 https://channel9.msdn.com/coding4fun/articles/MissionControl-A-Flexible-API-for-Remote-Device-Control/RSS Networking Windows Windows Phone Philips Hue Lighting Controller clip_image002 So Philips recently introduced their Hue Connected Bulbs: an easy-to-use set of LED light bulbs and Wi-Fi connected bridge which allows you to dynamically change the color of your home lighting using their iOS or Android app. What’s particularly cool is that the bridge has a web API which you can access to set the colors of each bulb with your own app. We at untitled network developed our own Philips Hue app called Oni: light Control, which is currently available on the Windows Phone Store. In addition to allowing you to set the color of your home lighting with defined “Moods”, the app also allows you to do the same using your phone’s built in voice commands or inexpensive NFC stickers. Here’s a demo of the Oni: Light Control in action: I’m going to show you how you can develop your own app using the color picker from the Coding4Fun Toolkit for Windows Phone and the Json.Net library from Newtonsoft. These libraries can be found on NuGet, but you’ll obviously need the Philips Hue Connected Bulbs kit to test things out. Getting Started: The Philips Hue API uses a restful JSON interface you can access using any http client. Documentation on all of the supported methods by the Philips Hue bridge can be found at http://blog.ef.net/2012/11/02/philips-hue-api.html. To get started, you’ll need authorized access to your bridge’s API. Once the bridge has successfully established a network connection with your router, discover its internal IP address via the URL: http://www.meethue.com/api/nupnp You should get a response similar to: [{"id":"ffss00fffe123456","internalipaddress":"192.168.1.100","macaddress":"0aa:bb:cc:dd:00:11"}] Note the internalipaddress value and use the IP to access the bridge’s API directly the with the URL http://192.168.1.100/api Now, since we haven’t registered a user for authorization, attempting to access the hub will return an error from the bridge: [{"error":{"type":1,"address":"/","description":"unauthorized user"}}] To register a new user, we’ll first POST the username we wish to use. var client = new WebClient(); //our uri to perform registration var uri = new Uri(string.Format("http://{0}/api", HostnameTextBox.Text)); //create our registration object, along with username and description var reg = new { username = UsernameTextBox.Text, devicetype = "Coding4Fun Hue Light Project" }; var jsonObj = JsonConvert.SerializeObject(reg); //decide what to do with the response we get back from the bridge client.UploadStringCompleted += (o, args) =] Dispatcher.BeginInvoke(() =] { try { ResponseTextBox.Text = args.Result; } catch (Exception ex) { ResponseTextBox.Text = ex.Message; } }); //Invoke a POST to the bridge client.UploadStringAsync(uri, jsonObj); Note the response we get back from our hub will be [{"error":{"type":101,"address":"","description":"link button not pressed"}}] This is because bridge requires you to first push the link button before new registrations can be made. After pushing the button and invoking the registration function again, you should receive the following result from the bridge: [{"success":{"username":"coding4fun"}}] settingScreen Setting the Bulb Color: We should now be able to access all methods on the bridge. You can get all of the configuration details, including all of the bulbs and their statuses with the same base url: http://192.168.1.100/api/coding4fun Now comes the fun part. There are three color modes in which you can use to set the color of your bulbs: • hue & sat: ‘hue’ is a color range between 0-65535 which represent 182.04*degrees, ‘sat’ is saturation with a range of 0-254 • xy: are coordinates in the CIE 1931 space • ct: is a color temperature expressed in mireds from 154 to 500, coolest to warmest respectfully Source: http://rsmck.co.uk/hue We’ll be setting the colors of our bulbs using hue & saturation parameters. Luckily, the Coding4Fun Toolkit for Windows Phone has three awesome color picker controls and some useful color extensions which makes setting the bulb colors a breeze. We start by building our state object – a list of parameters we want our bulb to be set to. Then we use the PUT verb to set the light with the following URL: http://{BRIGE-IPADDRESS}/api/coding4fun/lights/1/state The “1” in the url is the 1-based index of the bulb you want to set. //Get the HSV Value from the currently selected color var hsv = LightColorSlider.Color.GetHSV(); //build our State object var state = new { on = true, hue = (int)(hsv.Hue * 182.04), //we convert the hue value into degrees by multiplying the value by 182.04 sat = (int)(hsv.Saturation * 254) }; //convert it to json: var jsonObj = JsonConvert.SerializeObject(state); //set the api url to set the state var uri = new Uri(string.Format("http://{0}/api/{1}/lights/{2}/state", HostnameTextBox.Text, UsernameTextBox.Text, LightIndexTextBox.Text)); var client = new WebClient(); //decide what to do with the response we get back from the bridge client.UploadStringCompleted += (o, args) => Dispatcher.BeginInvoke(() => { try { ResponseTextBox.Text = args.Result; } catch (Exception ex) { ResponseTextBox.Text = ex.Message; } }); //Invoke the PUT method to set the state of the bulb client.UploadStringAsync(uri, "PUT", jsonObj); colorScreen That’s it! Be sure to check out all of the other functions the (other functions the Hue API supports) at http://developers.meethue.com/index.html Bio: Jarem Archer is a self-taught Software Developer and UX Designer. He’s part of a small team at untitled network who have a passion for video games, digital motion, entertainment and gadgets. Follow him on Twitter at http://twitter.com/unt1tled. ]]> https://channel9.msdn.com/coding4fun/articles/Philips-Hue-Lighting-Controller So Philips recently introduced their Hue Connected Bulbs: an easy-to-use set of LED light bulbs and Wi-Fi connected bridge which allows you to dynamically change the color of your home lighting using their iOS or Android app. What’s particularly cool is that the bridge has a web API which you can access to set the colors of each bulb with your own app. We at untitled network developed our own Philips Hue app called Oni: light Control, which is currently available on the Windows Phone Store. In addition to allowing you to set the color of your home lighting with defined “Moods”, the app also allows you to do the same using your phone’s built in voice commands or inexpensive NFC stickers. Here’s a demo of the Oni: Light Control in action: I’m going to show you how you can develop your own app using the color picker from the Coding4Fun Toolkit for Windows Phone and the Json.Net library from Newtonsoft. These libraries can be found on NuGet, but you’ll obviously need the Philips Hue Connected Bulbs kit to test things out. Getting Started: The Philips Hue API uses a restful JSON interface you can access using any http client. Documentation on all of the supported methods by the Philips Hue bridge can be found at http://blog.ef.net/2012/11/02/philips-hue-api.html. To get started, you’ll need authorized access to your bridge’s API. Once the bridge has successfully established a network connection with your router, discover its internal IP address via the URL: http://www.meethue.com/api/nupnp You should get a response similar to: [{&quot;id&quot;:&quot;ffss00fffe123456&quot;,&quot;internalipaddress&quot;:&quot;192.168.1.100&quot;,&quot;macaddress&quot;:&quot;0aa:bb:cc:dd:00:11&quot;}] Note the internalipaddress value and use the IP to access the bridge’s API directly the with the URL http://192.168.1.100/api Now, since we haven’t registered a user for authorization, attempting to access the hub will return an error from the bridge: [{&quot;error&quot;:{&quot;type&quot https://channel9.msdn.com/coding4fun/articles/Philips-Hue-Lighting-Controller Mon, 08 Apr 2013 15:17:51 GMT https://channel9.msdn.com/coding4fun/articles/Philips-Hue-Lighting-Controller Clint Rutkas, Jarem Archer Clint Rutkas, Jarem Archer 13 https://channel9.msdn.com/coding4fun/articles/Philips-Hue-Lighting-Controller/RSS C# Hardware Windows Phone Dynamic Lockscreen Changer for Windows Phone 8, Built With ASP.NET MVC and Azure Mobile Services With the release of Windows Phone 8, a few new developer API endpoints were made available that allow third-party applications to change the device lockscreen image. In this article, I am establishing the infrastructure and building a mobile application that provides the ability to choose from a number of dynamic image sets, from which images can be selected and then cycled as lockscreen wallpapers. What do you need You will need to download and install ASP.NET MVC3 to work on the web frontend and Windows Phone 8 SDK to work on the mobile applications. An Azure Mobile Services account will be necessary, and of course don’t forget to download and install the Azure Mobile Services client libraries. All three components are available at no additional charge. NOTE: Without the Azure Mobile Services SDK installed on the development machine, the compilation process will fail for the Windows Phone application. Setting up The Data Store First we need to establish the general design of the application and organize the workflow. The application will provide two ways to assign the dynamic lockscreen: • With the help of custom image sets that are provided by the service; • With the help of self-created image sets, aggregated from images provided by the service but ultimately managed by the end-user. Let’s talk about the general data model. Every image belongs to a certain category and to keep track of each we need a table with two columns—category ID and category name. We also need another core table containing the image references themselves, with the following columns: image URL, descriptive name, and the category ID to which it belongs. The overall structure looks like this: clip_image001 Now to the Windows Azure Management Portal and creating a new Mobile Service. clip_image003 Once created, you need to specify database information, just like you would with a standard SQL Server database: clip_image005 As the database is being created, you can easily integrate it with SQL Server Management Studio. You will need the server address, which may be obtained in the Azure Management Portal. To login, use the credentials that you set when creating the core database. Create the two tables mentioned above, with the following column configuration: Categories • ID - int • Name – varchar(100) Images • ID – int • URL – varchar(500) • Name – varchar(100) • CategoryID – int You can create these tables either in the SQL Server Management Studio or through the Azure Management Portal. However, you will need the Management Studio to create the column structure, as the Azure Management Portal does not offer this functionality right now. By default, the id column will be created automatically. To add the Name column to the Categories table, run this query: ALTER TABLE c4flockscreen.Categories ADD Name VARCHAR(100) To add the missing columns to the Images table, simply execute this query: ALTER TABLE c4flockscreen.Images ADD URL VARCHAR(500), Name VARCHAR(100), CategoryID INT Now that the database is ready, we’ll proceed to working on the web layer, which will effectively be the administrative portal for the service. Creating the Web Portal There should be a way to easily manage images and constantly expand the collection of possible lockscreen wallpapers. One way to do this is create a basic management portal that can carry basic CRUD operations. Start by creating an empty project: clip_image007 If you are not yet aware of the Model-View-Controller (MVC) development pattern, here is a good read explaining the fundamentals. Create a new controller in the Controllers folder, named HomeController. This will be the only controller created in this project. For now, add an ActionResult-based function that will return the main view: using System.Web.Mvc; namespace Coding4Fun.Lockscreen.Web.Controllers { public class HomeController : Controller { public ActionResult MainView() { return View(); } } } Having the controller without the proper views is pointless, so create a new view in Views/Home and name it MainView. For now, do not focus on the visual layout of the page, but rather on the functional aspect of the web frontend. If you run the application now, you will most likely get a 404 response. That is because the associated home view is by default not found. Open App_Start/RouteConfig.cs and make sure that the default view is set to MainView instead of Index. routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "MainView", id = UrlParameter.Optional } ); The core is created and now if running the web application you will see a basic HTML page: clip_image009 We now need to handle data from the Azure Mobile Services database. Out-of-the-box, there is no ASP.NET SDK available, but the database can be easily accessed through a REST API. But before that, we need to define the data models for the Categories and Images table. Begin by creating two classes in the Models folder: Category.cs: public class Category { public int? id { get; set; } public string Name { get; set; } } Image.cs: public class Image { public int? id { get; set; } public string URL { get; set; } public string Name { get; set; } public int CategoryID { get; set; } } Each of the properties is tied to the associated column in the database we created earlier. Notice that the ID values are nullable. This is introduced because the index will by default be automatically assigned. When new instances of Category or Image are created, I will not explicitly set the id property, so keeping it null instead of at a potential default value of 0 will ensure that it is properly set on the backend. Let’s now create the connectivity engine that will allow us to query the content of the data store. For this purpose, I created a DataStore folder and a DataEngine class inside it. We will need a unique API key for each of our requests, so open the Azure Management Portal and obtain it from there: clip_image010 In order to keep consistency between projects, and to be able to re-use the same Azure Mobile Services API key and core URL, I created an AuthConstants class in the context of the Coding4Fun.Lockscreen.Core project. It carries three static fields: public static class AuthConstants { public static string AmsApiKey = "YOUR_KEY_HERE"; public const string AmsUrl = "https://c4flockscreen.azure-mobile.net/"; public const string AmsTableUrl = AmsUrl + "tables/"; } Back in the ASP.NET project, the query operations are carried with the help of HttpClient initialized in the class constructor, which also includes the key used to authenticate the requests via the X-ZUMO-APPLICATION header: private HttpClient client; public DataEngine() { client = new HttpClient(); client.DefaultRequestHeaders.Add("X-ZUMO-APPLICATION", KEY); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); } This is the basic data harness. I also implemented two core methods in order to get all existing categories: public IEnumerable<Category> GetAllCategories() { var result = client.GetStringAsync(string.Concat(CORE_URL,"Categories")).Result; IEnumerable<Category> categories = JsonConvert.DeserializeObject<IEnumerable<Category>>(result); return categories; } And images: public IEnumerable<Image> GetAllImages() { var result = client.GetStringAsync(string.Concat(CORE_URL, "Images")).Result; IEnumerable<Image> images = JsonConvert.DeserializeObject<IEnumerable<Image>>(result); return images; } For each of these, a basic request is made with the table name appended to the base URL (represented by the CORE_URL constant). Since JSON.NET is now bundled with ASP.NET, I am able to easily deserialize the returned JSON data array to an IEnumerable<Type>. There is one problem, however, with the GetAllImages approach. It implies that even if I want to use LINQ to query the existing image collection, I have to first download the entire set locally. Fortunately, the Azure Mobile Services REST API provides an endpoint with filtering, and that’s what I am using in GetCategoryById and GetImagesByCategoryId: public Category GetCategoryById(int id) { string composite = string.Concat(CORE_URL, "Categories?$filter=(id%20eq%20", id.ToString(), ")"); var result = client.GetStringAsync(composite).Result; IEnumerable<Category> categories = JsonConvert.DeserializeObject<IEnumerable<Category>>(result); return categories.FirstOrDefault(); } public IEnumerable<Image> GetImagesByCategoryId(int id) { string composite = string.Concat(CORE_URL, "Images?$filter=(CategoryID%20eq%20", id.ToString(), ")"); var result = client.GetStringAsync(composite).Result; IEnumerable<Image> images = JsonConvert.DeserializeObject<IEnumerable<Image>>(result); return images(); } Notice the ?$filter= parameter, in which the conditional is URL encoded and is wrapped in parentheses. For the category query, I am checking the id value, and for the image I’m checking CategoryID. In the Views/Home folder, create a new view and name it Images. It will be used to list existing images that are associated with one of the selected categories. You also need to adjust the controller code to handle the incoming data: using Coding4Fun.Lockscreen.Web.DataStore; using System.Web.Mvc; namespace Coding4Fun.Lockscreen.Web.Controllers { public class HomeController : Controller { DataEngine engine; public HomeController() { engine = new DataEngine(); } public ActionResult MainView() { var categories = engine.GetAllCategories(); return View(categories); } public ActionResult Images(int categoryId) { var images = engine.GetImagesByCategoryId(categoryId); if (images != null) { return View(images); } return View("MainView"); } } } For the main view, I am getting the list of categories and passing them as the bound model. For the Images view, the category ID is passed as an argument that will later enable the engine to return a list of all images that have CategoryID set to that value. In case the returned list is not null, the view is shown. Otherwise, the main view is the terminal point. In its current state, I’ll be able to use the frontend to list existing categories and images, but not to add, remove, or update items. Adding a category and an image is a matter of modifying an HttpClient request, with the help of HttpRequestMessage. For example, here is how I can add a category through my DataEngine class: public HttpStatusCode AddCategory(Category category) { var serializedObject = JsonConvert.SerializeObject(category, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); var request = new HttpRequestMessage(HttpMethod.Post, string.Concat(CORE_URL, "Categories")); request.Content = new StringContent(serializedObject, Encoding.UTF8, "application/json"); var response = client.SendAsync(request).Result; return response.StatusCode; } JSON.NET capabilities are used to serialize the object that needs to be inserted. The POST request is executed against the standard table URL, with the UTF8 encoded JSON string. Since the client is already carrying the basic authentication header, all that needs to be done is calling the SendAsync function. Updating a category follows the same approach, though a PATCH method is used for the request and the URL contains the index of the category that needs to be updated: public HttpStatusCode UpdateCategory(Category category) { var request = new HttpRequestMessage(new HttpMethod("PATCH"), string.Concat(CORE_URL, "Categories", "/", category.id)); var serializedObject = JsonConvert.SerializeObject(category); request.Content = new StringContent(serializedObject, Encoding.UTF8, "application/json"); var response = client.SendAsync(request).Result; return response.StatusCode; } To delete a category from the data store, one simply needs to pass a parameter to it that identifies the index of the category that needs to be removed: public HttpStatusCode DeleteCategoryFromId(int categoryId) { var request = new HttpRequestMessage(HttpMethod.Delete, string.Concat(CORE_URL, "Categories", "/", categoryId)); var response = client.SendAsync(request).Result; return response.StatusCode; } For images, the same methods can be used, with the Images table passed as the name for the target in the composite URL. Let’s now get back to working on some of the views. A static category list is not fun, so let’s create a way to add new categories. Right click on the Views/Home folder and select Add View: clip_image012 A great thing about the view creation process in Visual Studio is the fact that you are able to use a basic scaffold template for a strongly-typed view. In this case, I am associating it with a Category class and using the Create template. I now need to modify the controller code to process requests to AddCategory. I need to handle two types of requests, GET and POST, because the view will be displayed to both add an item and submit an item: public ActionResult AddCategory() { return View(); } [HttpPost] public ActionResult AddCategory(Category category) { if (ModelState.IsValid) { engine.AddCategory(category); return RedirectToAction("MainView"); } return View(); } For a GET request, I am simply returning the view. For a POST view, I am adding the category that was defined by the bound model through the local DataEngine instance, after which the user is redirected to the main view. But we also need to add an ActionResult for the MainView to obtain the list of items that are currently in the Categories table: public ActionResult MainView() { var categories = engine.GetAllCategories(); return View(categories); } The DataEngine instance will return all categories in an IEnumerable<Category> form that are passed as the model for the main view. The layout of MainView.cshtml can be as simple as a table: @{ ViewBag.Title = "Coding4Fun Dynamic Lockscreen"; } <h2>Coding4Fun Dynamic Lockscreen - Categories</h2> <table> <tr> <td> <b>ID</b> </td> <td> <b>Category Name</b> </td> </tr> @foreach (var p in Model) { <tr> <td> @p.id </td> <td> @p.Name </td> <td> @Html.ActionLink("Images", "Images", new { categoryId = p.id }) </td> <td> @Html.ActionLink("Edit", "EditCategory", new { categoryId = p.id }) </td> <td> @Html.ActionLink("Delete", "DeleteCategory", new { categoryId = p.id }) </td> </tr> } </table> @Html.ActionLink("Add Category", "AddCategory") The ActionLink helper allows me to invoke a view and, if necessary, pass specific parameters to it (e.g., when I need to identify the category that needs to be deleted or edited). Some of the views listed here are not yet created, but I can easily use placeholder names in any case. The ultimate result for the main page will look like this: clip_image013 Notice that you are also able to add new categories now by clicking on the Add Category link on the bottom. This will redirect you to the AddCategory view that we created: clip_image014 Let’s see how to implement the category editing in the web frontend. First of all, create a new view in Views/Home and name it EditCategory. Use the Edit scaffold template. Like AddCategory, EditCategory needs to be handled in two separate ways for GET and POST requests in the controller: public ActionResult EditCategory(int categoryId) { Category category; category = engine.GetCategoryById(categoryId); if (category != null) return View(category); return View("MainView"); } [HttpPost] public ActionResult EditCategory(Category category) { if (ModelState.IsValid) { engine.UpdateCategory(category); return RedirectToAction("MainView"); } return View(); } For a GET request, we need to identify the category that needs to be added by its index, so we are using a categoryId argument passed to the view, which is later used by the DataEngine instance to retrieve the category from the data store. For a POST action, the implementation for UpdateCategory from above is used, where a PATCH request is run with the serialized object bound to the view. For the Delete action, no additional view is necessary but the controller still needs a handler, so we can use a snippet like this: public ActionResult DeleteCategory(int categoryId) { engine.DeleteCategoryFromId(categoryId); return RedirectToAction("MainView"); } You can use the same approach to add, delete, and edit items in the list of images. For adding images, however, you might want to pass the category identifier. When images are listed after the category has been selected, it is necessary to provide a way to identify the category to which new entities should be added. To do this, we can. in the main controller. pass the category index to the view when the Images action is being triggered: public ActionResult Images(int categoryId) { var images = engine.GetImagesByCategoryId(categoryId); if (images != null) { ViewData["CID"] = categoryId; return View(images); } return View("MainView"); } Afterwards, the categoryId value can be obtained by using the CID key for ViewData inside the view itself. Let’s now take a look at how images are represented for each category. I created a custom view to list all the images associated with the Images category. If you look above at the controller code, you will notice that I am passing the category ID, through which the image set query is executed, and the returned collection is set as the bound model: public ActionResult Images(int categoryId) { var images = engine.GetImagesByCategoryId(categoryId); if (images != null) { ViewData["CID"] = categoryId; return View(images); } return View("MainView"); } When an image needs to be added, call the AddImage view. In HomeController.cs, it carries implementations for both GET and POST requests: public ActionResult AddImage(int categoryId) { Image image = new Image(); image.CategoryID = categoryId; return View(image); } [HttpPost] public ActionResult AddImage(HttpPostedFileBase file, Image image) { if (file != null && file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath("~/Uploads"), image.CategoryID.ToString(), fileName); string dirPath = Path.GetDirectoryName(path); if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath); file.SaveAs(path); string applicationUrl = string.Format("{0}://{1}{2}", HttpContext.Request.Url.Scheme, HttpContext.Request.ServerVariables["HTTP_HOST"], (HttpContext.Request.ApplicationPath.Equals("/")) ? string.Empty : HttpContext.Request.ApplicationPath ); image.URL = Path.Combine(applicationUrl, "Uploads", image.CategoryID.ToString(), fileName); } if (ModelState.IsValid && image.URL != null) { engine.AddImage(image); return RedirectToAction("Images", new { categoryID = image.CategoryID }); } return View(); } When a GET request is executed against the AddImage endpoint, I pass the category ID as the flag, signaling which category the image should be included in. When a POST request is executed, it can go two ways—either the user is passing an existing link to a hosted image or the user is uploading his own image to the local server. When an upload is inbound, HttpPostedFileBase carries the content that needs to be pushed to the server. The upload component on the view itself is done by creating a form with a file input: <h2>Or you could upload your own file: </h2> @if (Model != null) { using (Html.BeginForm("AddImage", "Home", FormMethod.Post, new { enctype = "multipart/form-data", image = Model })) { @Html.HiddenFor(model => model.CategoryID); <input type="file" name="file" /> <input type="submit" value="OK" /> } } If there is no file selected, the system assumes that the user just decided to add an existing URL. It’s important to mention that the upload workflow relies on the availability of the Upload folder. It is created by default when the project is deployed to the server, but you also need to make sure that the ASP.NET user on the machine where IIS is located has the appropriate write permission for the folder. The Windows Phone 8 Application Foundation Create a new Windows Phone 8 application and add a reference to Windows Azure Mobile Services Managed Client. It should be available in the Extensions section if you installed the Windows Azure Mobile Services SDK as I mentioned at the beginning of the article: clip_image016 In App.xaml.cs you need to create an instance of MobileServiceClient that will be used as the central connection point to the database. Notice that I am using the predefined AMS and API KEY string constants: public static MobileServiceClient MobileService = new MobileServiceClient(AuthConstants.AmsUrl, AuthConstants.AmsApiKey); The mobile application should also carry the data models for both the categories and images. That said, we can reorganize those a bit for a more convenient data binding layout. To ensure that we can reuse the classes from different application components, I am once again using the Coding4Fun.Lockscreen.Core project. Create a new folder called Models and add a new class called Category: using System.Collections.ObjectModel; namespace Coding4Fun.Lockscreen.Core.Models { public class Category { public Category() { Images = new ObservableCollection<Image>(); } public int? id { get; set; } public string Name { get; set; } public ObservableCollection<Image> Images { get; set; } public override string ToString() { return Name; } } } We are still relying on a nullable index value, but now there is an ObservableCollection for images. The reason for using this specific collection type is because with an ObservableCollection, binding updates are performed automatically when new items are added or removed, therefore cutting the need to implement the notification mechanism. The ToString function is overridden to simplify data extraction on binding. When a collection with categories will be hooked to a list, for example, I don’t have to create a converter or a property link. For the Image model, create a new class called Image in the same Models folder: namespace Coding4Fun.Lockscreen.Core.Models { public class Image { public int? id { get; set; } public string URL { get; set; } public string Name { get; set; } public int CategoryID { get; set; } } } Application Workflow & Storage Let’s talk about how image categories will be handled in the application. On application startup, the database is queried for the available categories and each of them is listed on the home screen. If the user taps on one of the categories, the database is queried for the images that are associated with the category index. However, the user should also be able to create his own custom categories that will only be available in-app. Those categories can carry images from multiple other categories, if necessary, with the default reference set to the internal storage. Since we are working with local storage, let’s create a helper class called LocalStorageHelper in the Coding4Fun.Lockscreen.Core project in the Storage folder. This class will carry basic read and write functions, allowing us to store data internally: public static class LocalStorageHelper { public async static void WriteData(string folderName, string fileName, byte[] content) { IStorageFolder rootFolder = ApplicationData.Current.LocalFolder; if (folderName != string.Empty) { rootFolder = await rootFolder.CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists); } IStorageFile file = await rootFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); using (var s = await file.OpenStreamForWriteAsync()) { s.Write(content, 0, content.Length); } } public static async void ClearFolder(string folderName) { var folder = await ApplicationData.Current.LocalFolder.GetFolderAsync(folderName); if (folder != null) { foreach (IStorageFile file in await folder.GetFilesAsync()) { await file.DeleteAsync(); } } } public static async Task<string> ReadData(string fileName) { byte[] data; StorageFolder folder = ApplicationData.Current.LocalFolder; StorageFile file = await folder.GetFileAsync(fileName); using (Stream s = await file.OpenStreamForReadAsync()) { data = new byte[s.Length]; await s.ReadAsync(data, 0, (int)s.Length); } return Encoding.UTF8.GetString(data, 0, data.Length); } } Notice that I am using the newly-introduced StorageFolder/StorageFile capabilities. If you worked with Windows Store application development, you are probably already familiar with them. Application.Current.LocalFolder gives me direct access to the local directory. which can be modified from within the application itself. It works in a manner similar to IsolatedStorageFile in Windows Phone 7, but with more flexibility when it comes to creating new folders and files and well doing file sweeps. As I mentioned above, there will be internal data stored as XML. For this purpose, I need a class that carries serialization and deserialization routines, and I can simplify this task by using the Coding4Fun Toolkit Serialize.Save<T> and Serialize.Open<T> capabilities. Calls to these functions allow flexible serialization, where by default the static class is not aware of the serialization type, but is instead able to dynamically infer it from the incoming data. Once the byte layout is obtained for the content, I use the LocalStorageHelper class to write it to a file. As there are multiple UI items that need to be bound to collections and object instances, I have a CentralBindingPoint class in my main project that is my main view model (it implements INotifyPropertyChanged). It implements the singleton pattern, so that the main instance is created on initialization and is subsequently re-used as necessary: using Coding4Fun.Lockscreen.Core.Models; using System; using System.Collections.ObjectModel; using System.ComponentModel; namespace Coding4Fun.Lockscreen.Mobile { public class CentralBindingPoint : INotifyPropertyChanged { static CentralBindingPoint instance = null; static readonly object padlock = new object(); public CentralBindingPoint() { Categories = new ObservableCollection<Category>(); CustomCategories = new ObservableCollection<Category>(); } public static CentralBindingPoint Instance { get { lock (padlock) { if (instance == null) { instance = new CentralBindingPoint(); } return instance; } } } private ObservableCollection<Category> _categories; public ObservableCollection<Category> Categories { get { return _categories; } set { if (_categories != value) { _categories = value; NotifyPropertyChanged("Categories"); } } } private ObservableCollection<Category> _customCategories; public ObservableCollection<Category> CustomCategories { get { return _customCategories; } set { if (_customCategories != value) { _customCategories = value; NotifyPropertyChanged("CustomCategories"); } } } private Category _currentCategory; public Category CurrentCategory { get { return _currentCategory; } set { if (_currentCategory != value) { _currentCategory = value; NotifyPropertyChanged("CurrentCategory"); } } } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String info) { if (PropertyChanged != null) { System.Windows.Deployment.Current.Dispatcher.BeginInvoke( () => { PropertyChanged(this, new PropertyChangedEventArgs(info)); }); } } } } On the main page, I create a Pivot-based layout to have an easy way to transition between the web collections (categories) and the local ones: Generic Episode Image For each of the collection types, there is a ListBox with a custom DataTemplate assigned for each item. The items are obtained from the Categories collection for web sets and the CustomCategories collection for local sets, both in the CentralBindingPoint view model. The categories are loaded with the help of the DataEngine class that I added in the Data folder in the main application project. It is a wrapper for the Azure Mobile Services data operations, allowing me to aggregate the list of categories and images, given that I know the category index: public class DataEngine { async public Task<List<Category>> GetCategoryList() { IMobileServiceTable<Category> table = App.MobileService.GetTable<Category>(); List<Category> data = await table.ToListAsync(); return data; } async public Task<List<Image>> GetImagesByCategoryId(int categoryId) { IMobileServiceTable<Image> table = App.MobileService.GetTable<Image>(); List<Image> data = await table.Where(x => x.CategoryID == categoryId).ToListAsync(); return data; } } When the main page loads, I use the local DataEngine instance to call GetCategoryList and obtain a List<Category> collection that is subsequently transformed into an ObservableCollection through one of the default constructors: async void MainPage_Loaded(object sender, RoutedEventArgs e) { CentralBindingPoint.Instance.Categories = new ObservableCollection<Category>(await dataEngine.GetCategoryList()); } When a category is selected in the web sets list, I assign the selected item as the current category and navigate to the ImageSetPage.xaml page that will display the associated images: async void ListBox_SelectionChanged_1(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { var box = (ListBox)sender; if (box.SelectedItem != null) { Category selectedCategory = (Category)box.SelectedItem; selectedCategory.Images = new ObservableCollection<Coding4Fun.Lockscreen.Core.Models.Image> (await dataEngine.GetImagesByCategoryId((int)selectedCategory.id)); CentralBindingPoint.Instance.CurrentCategory = selectedCategory; NavigationService.Navigate(new Uri("/ImageSetPage.xaml", UriKind.Relative)); } } Notice that the images are not loaded at the same time as the categories; rather, they’re loaded only when a category has been selected, hence the GetImagesByCategoryId call on selection. For a custom set, the procedure is pretty much the same, the only difference being the fact that image references are already present since those were deserialized from the local storage: private void lstCustomSets_SelectionChanged_1(object sender, SelectionChangedEventArgs e) { var box = (ListBox)sender; if (box.SelectedItem != null) { Category selectedCategory = (Category)box.SelectedItem; CentralBindingPoint.Instance.CurrentCategory = selectedCategory; NavigationService.Navigate(new Uri("/ImageSetPage.xaml", UriKind.Relative)); } } In ImageSetPage.xaml I use a ListBox with a WrapPanel in the ItemsPanelTemplate, which ensures that I can have only two images in a row and any additions will be wrapped, with a fixed row length. You can get that control from the WPToolkit (formerly known as Silverlight Toolkit for Windows Phone, available on NuGet). Generic Episode Image Here is the basic XAML layout: <ListBox SelectionMode="Single" Margin="24" x:Name="lstImages" SelectionChanged="lstImages_SelectionChanged_1" ItemsSource="{Binding Path=Instance.CurrentCategory.Images, Source={StaticResource CentralBindingPoint}}" ItemTemplate="{StaticResource ListItemTemplate}"> <ListBox.ItemsPanel> <ItemsPanelTemplate> <toolkit:WrapPanel ItemWidth="216" ItemHeight="260"/> </ItemsPanelTemplate> </ListBox.ItemsPanel> </ListBox> Now that we have a basic skeleton for the incoming data, let’s see how it can be transformed into a live lockscreen, on which wallpapers can be cycled. In the ImageSetPage.xaml page I have a button in the application bar that allows me to set the current category as the source for the switching wallpapers. Currently, each Image instance carries an image URL and the images can be located anywhere outside the application. This can cause problems with the wallpaper setting process, however, since the API only allows local images to be set as background. This means that I need to download each image to the local application folder: private async void btnSetStack_Click_1(object sender, EventArgs e) { var isProvider = Windows.Phone.System.UserProfile.LockScreenManager.IsProvidedByCurrentApplication; if (!isProvider) { var op = await Windows.Phone.System.UserProfile.LockScreenManager.RequestAccessAsync(); isProvider = op == Windows.Phone.System.UserProfile.LockScreenRequestResult.Granted; } if (isProvider) { downloadableItems = new List<string>(); fileItems = new List<string>(); foreach (var image in CentralBindingPoint.Instance.CurrentCategory.Images) { downloadableItems.Add(image.URL); fileItems.Add(Path.GetFileName(image.URL)); } SerializationHelper.SerializeToFile(fileItems, "imagestack.xml"); LocalStorageHelper.ClearFolder("CurrentSet"); DownloadImages(); grdDownloading.Visibility = System.Windows.Visibility.Visible; } } First of all, I need to make sure that the application can set a lockscreen background and is registered in the OS as a provider. The application needs to state its intent to be able to access the wallpaper by adding this snippet to the WMAppManifest.xml, right after the Tokens node: <Extensions> <Extension ExtensionName="LockScreen_Background" ConsumerID="{111DFF24-AA15-4A96-8006-2BFF8122084F}" TaskID="_default" /> </Extensions> downloadableItems is a collection that represents the download queue. fileItems contains the local file names for each image that is about to be downloaded and will be serialized and used in the background agent to iterate through the category files. Whenever the download process is started, an overlay becomes visible to notify the user that the image acquisition process is in progress. Also, notice the fact that I am calling LocalStorageHelper.ClearFolder, passing the name of the folder as the first argument. I do not want to keep images for sets that are not active, therefore when a new set is selected, the currently stored images are deleted from the CurrentSet folder and replaced by the ones that are about to be downloaded. The implementation of the ClearFolder function looks like this: public static void ClearFolder(string folderName { if (store.DirectoryExists(folderName)) { foreach (string file in store.GetFileNames(folderName + "\\*.*")) { store.DeleteFile(folderName + "\\" + file); } } } Once the file names are stored in imagestack.xml, the image contents are downloaded via DownloadImages: void DownloadImages() { WebClient client = new WebClient(); string fileName = Path.GetFileName(downloadableItems.First()); client.OpenReadAsync(new Uri(downloadableItems.First())); client.OpenReadCompleted += (sender, args) => { Debug.WriteLine("Downloaded " + fileName); LocalStorageHelper.WriteData("CurrentSet", fileName, StreamToByteArray(args.Result)); downloadableItems.Remove(downloadableItems.First()); if (downloadableItems.Count != 0) DownloadImages(); else { grdDownloading.Visibility = System.Windows.Visibility.Collapsed; LocalStorageHelper.CycleThroughImages(); //ScheduledActionService.LaunchForTest("LockscreenChanger", TimeSpan.FromSeconds(5)); } }; } Here you can see that I am making a call to LocalStorageHelper.CycleThroughImages—a function that reads the file that contains the current set and picks the first image, assigning it to be the current wallpaper and then pushing it to the back of the list, making the succeeding image the next in line for the wallpaper: public static void CycleThroughImages() { List<string> images = Coding4Fun.Phone.Storage.Serialize.Open<List<string>>("imagestack.xml"); if (images != null) { string tempImage = images.First(); Uri currentImageUri = new Uri("ms-appdata:///Local/CurrentSet/" + tempImage, UriKind.Absolute); Windows.Phone.System.UserProfile.LockScreen.SetImageUri(currentImageUri); images.Remove(tempImage); images.Add(tempImage); Coding4Fun.Phone.Storage.Serialize.Save<List<string>>("imagestack.xml", images); } } You might be wondering why I’m not using Queue<T> for this. After all, Enqueue and Dequeue would make things a bit easier. The problem is that a Queue instance cannot be directly serialized without being transformed to a flat list. Therefore, I am sticking to minimal resource processing by manipulating a List<T> instance instead. The recursive image download method runs until the download queue is emptied, after which the overlay is hidden. Background Agent At this point, we have the images locally stored and listed in an XML file. If the user accepted the system prompt, the application has also been registered as a lockscreen background provider, but there is not yet a single piece of code that would actually set the wallpaper cycle. For that, create a new Background Agent project in your solution. I named mine Coding4Fun.Lockscreen.Agent. The OnInvoke function in ScheduledAgent.cs is executed at 30-minute intervals. This is a time limit defined by the PeriodicTask background agent type that we’ll be using here. You need to add the following snippet to it: protected override void OnInvoke(ScheduledTask task) { var isProvider = Windows.Phone.System.UserProfile.LockScreenManager.IsProvidedByCurrentApplication; if (isProvider) { LocalStorageHelper.CycleThroughImages(); } NotifyComplete(); } As with the download snippet, I am ensuring that before I attempt to change the wallpaper the application is a registered provider. Otherwise, an exception will be thrown and the background agent will crash. The bad thing about periodic tasks crashing is the fact that once two consecutive crashes occur, the task is removed from the task queue and the backgrounds will not be changed. If the application is a provider, call CycleThroughImages to set the new background and push the old one to the end of the list. To make sure that a different image is selected each time, the original deserialized list is modified, where the first image now becomes last, switching the stack up, after which it is serialized back into imagestack.xml. The background agent needs to be registered in the WMAppManifest.xml. Inside the Tasks node, add an ExtendedTask: <ExtendedTask Name="LockscreenChangerTask"> <BackgroundServiceAgent Specifier="ScheduledTaskAgent" Name="LockscreenChanger" Source="Coding4Fun.Lockscreen.Agent" Type="Coding4Fun.Lockscreen.Agent.ScheduledAgent" /> </ExtendedTask> Also, when the application starts, you need to ensure that the task is registered, and register it if it isn’t yet. Use the Application_Launching event handler for this task: private void Application_Launching(object sender, LaunchingEventArgs e) { string taskName = "LockscreenChanger"; var oldTask = ScheduledActionService.Find(taskName) as PeriodicTask; if (oldTask != null) { ScheduledActionService.Remove(taskName); } PeriodicTask task = new PeriodicTask(taskName); task.Description = "Change lockscreen wallpaper."; ScheduledActionService.Add(task); LoadCustomCategories(); } Here, LoadCustomCategories will deserialize the existing custom categories, so that those can be shown in the main page after the application starts: private async void LoadCustomCategories() { try { CentralBindingPoint.Instance.CustomCategories = (ObservableCollection<Category>)await SerializationHelper.DeserializeFromFile( typeof(ObservableCollection<Category>), "customcat.xml"); } catch { Debug.WriteLine("No customcat.xml - no registered custom categories."); } } Now the backgrounds will automatically change based on the web sets that you will activate every 30 minutes. Working with Custom Categories Let’s create some custom sets. To manage user input, I leverage the CustomMessageBox control available in the Windows Phone Toolkit. It has enough flexibility to let me choose between adding a TextBox control, to have the user create the new category or use a ListPicker to show the available custom categories in a consistent UI layout. When the user decides to create a new category, he taps the plus button in the application bar on the main page: clip_image022 The implementation for the call is simple: private void btnSetStack_Click_1(object sender, EventArgs e) { TextBox textBox = new TextBox(); CustomMessageBox box = new CustomMessageBox() { Caption = "Add Custom Category", Message = "Enter a unique name for the new category.", LeftButtonContent = "ok", RightButtonContent = "cancel", Content = textBox }; box.Dismissed += (s, boxEventArgs) => { if (boxEventArgs.Result == CustomMessageBoxResult.LeftButton) { if (!string.IsNullOrWhiteSpace(textBox.Text)) { var categoryCheck = (from c in CentralBindingPoint.Instance.CustomCategories where c.Name == textBox.Text select c).FirstOrDefault(); if (categoryCheck == null) { Category category = new Category() { Name = textBox.Text }; CentralBindingPoint.Instance.CustomCategories.Add(category); Coding4Fun.Toolkit.Storage.Serialize.Save<ObservableCollection<Category>>( "customcat.xml", CentralBindingPoint.Instance.CustomCategories); } else { MessageBox.Show("Add Custom Category", "This category name was already taken!", MessageBoxButton.OK); } } } }; box.Show(); } When the message box is dismissed, I check which button is pressed to take the appropriate course of action. Let’s assume that the user decided to add the new category—we need to check and make sure that there isn’t already a category with the same name in the existing collection. If there isn’t one, a new Category instance is created, added to the collection in the main view model, and serialized to customcat.xml. The user also needs to be able to add images from any category to another custom category. To do this, I decided to give the user the option to carry across the image name and URL when he taps on an image in the ImageSetPage.xaml. Remember, if there are no current custom categories registered, the user should be informed that he should create some first, so the alternative route for the dialog with custom category name selection should be a message box alert: clip_image024 Here is the snippet that does this: private void lstImages_SelectionChanged_1(object sender, SelectionChangedEventArgs e) { if (CentralBindingPoint.Instance.CustomCategories.Count > 0) { if (lstImages.SelectedItem != null) { ListPicker picker = new ListPicker() { Header = "Custom category name:", ItemsSource = CentralBindingPoint.Instance.CustomCategories, Margin = new Thickness(12, 42, 24, 18) }; CustomMessageBox messageBox = new CustomMessageBox() { Caption = "Add To Custom Category", Message = "Select a registered custom category to add this image to.", Content = picker, LeftButtonContent = "ok", RightButtonContent = "cancel" }; messageBox.Dismissing += (s, boxEventArgs) => { if (picker.ListPickerMode == ListPickerMode.Expanded) { boxEventArgs.Cancel = true; } }; messageBox.Dismissed += (s2, e2) => { switch (e2.Result) { case CustomMessageBoxResult.LeftButton: { if (picker.SelectedItem != null) { Category category = (from c in CentralBindingPoint.Instance.CustomCategories where c.Name == picker.SelectedItem.ToString() select c).FirstOrDefault(); if (category != null) { category.Images.Add((Coding4Fun.Lockscreen.Core.Models.Image)lstImages.SelectedItem); Coding4Fun.Toolkit.Storage.Serialize.Save<ObservableCollection<Category>>( "customcat.xml", CentralBindingPoint.Instance.CustomCategories); } lstImages.SelectedItem = null; lstImages.IsEnabled = true; } break; } case CustomMessageBoxResult.RightButton: case CustomMessageBoxResult.None: { lstImages.SelectedItem = null; break; } } }; messageBox.Show(); } } else { MessageBox.Show("Add To Custom Category", "Tapping on an image will prompt you to add it to a custom category" + Environment.NewLine + "Seems like you don't have any custom categories yet.", MessageBoxButton.OK); } } Once the category is selected from the list, the image is added to the Images collection in the Category instance, and the category list is serialized to preserve the changes. There are no restrictions as to which categories can fetch images to other categories—we can even select images from custom categories and include them in other categories. The image can be added multiple times to the same category as well. Conclusion With Azure Mobile Services and a managed SDK available for Windows Phone, as well as an open REST API, it is fairly easy to build connected applications on multiple platforms at once without major logic and code base modifications. ]]> https://channel9.msdn.com/coding4fun/articles/Dynamic-Lockscreen-Changer-for-Windows-Phone-8-Built-With-ASPNET-MVC-and-Azure-Mobile-Services With the release of Windows Phone 8, a few new developer API endpoints were made available that allow third-party applications to change the device lockscreen image. In this article, I am establishing the infrastructure and building a mobile application that provides the ability to choose from a number of dynamic image sets, from which images can be selected and then cycled as lockscreen wallpapers. What do you needYou will need to download and install ASP.NET MVC3 to work on the web frontend and Windows Phone 8 SDK to work on the mobile applications. An Azure Mobile Services account will be necessary, and of course don’t forget to download and install the Azure Mobile Services client libraries. All three components are available at no additional charge. NOTE: Without the Azure Mobile Services SDK installed on the development machine, the compilation process will fail for the Windows Phone application. Setting up The Data StoreFirst we need to establish the general design of the application and organize the workflow. The application will provide two ways to assign the dynamic lockscreen: With the help of custom image sets that are provided by the service; With the help of self-created image sets, aggregated from images provided by the service but ultimately managed by the end-user. Let’s talk about the general data model. Every image belongs to a certain category and to keep track of each we need a table with two columns—category ID and category name. We also need another core table containing the image references themselves, with the following columns: image URL, descriptive name, and the category ID to which it belongs. The overall structure looks like this: Now to the Windows Azure Management Portal and creating a new Mobile Service. Once created, you need to specify database information, just like you would with a standard SQL Server database: As the database is being created, you can easily integrate it with SQL Server Management Studio. You will need the se https://channel9.msdn.com/coding4fun/articles/Dynamic-Lockscreen-Changer-for-Windows-Phone-8-Built-With-ASPNET-MVC-and-Azure-Mobile-Services Mon, 25 Mar 2013 15:39:25 GMT https://channel9.msdn.com/coding4fun/articles/Dynamic-Lockscreen-Changer-for-Windows-Phone-8-Built-With-ASPNET-MVC-and-Azure-Mobile-Services Clint Rutkas, Den Delimarsky Clint Rutkas, Den Delimarsky 0 https://channel9.msdn.com/coding4fun/articles/Dynamic-Lockscreen-Changer-for-Windows-Phone-8-Built-With-ASPNET-MVC-and-Azure-Mobile-Services/RSS Azure MVC Windows Phone Windows Azure Mobile Services Azure Mobile Services Panoramic Camera Head The Pano Head is a rotating platform for a camera that mounts on a tripod and is controlled from your Windows Phone 8 device over Bluetooth. You can use it to take a series of pictures that you can stitch up with Photosynth. I’ve always wanted to take panoramic pictures with my camera from a tripod, so I decided to make a remote controlled panoramic tripod head that would screw on to any tripod. Using a motor and a shutter control, a series of pictures can be taken. With the use of Photosynth, those pictures can be stitched up to make an interactive 360-degree view. You can also use your Windows Phone 8 as a remote shutter release over a Bluetooth connection. Windows Phone 8 has a Bluetooth API that allows us to program connectivity using TCP/IP style sockets. This is a popular project in the Arduino world and I wanted to complete it using Gadgeteer hardware and the .NET Micro Framework (NETMF). This project uses the FEZ Cereberus mainboard module, but you should be able to use other Gadgeteer mainboards without any problems. What is the .NET Gadgeteer platform? The .NET Gadgeteer platform is an open source toolkit for building small electronic projects using Gadgeteer hardware modules and programmed using the .NET Micro Framework with Visual Studio 2010 or Visual C# Express (2010 edition). The Gadgeteer modules connect together using special cables and very little soldering is required. You typically use a mainboard module, which has the CPU and memory, and then connect various modules (camera, sensors, networking, display, controllers, etc) to accomplish your chosen task. This part is going to require Visual Studio 2010 C#. Whether the full version or the Express version, it has to be 2010. This is because the Gadgeteer libraries have as of this writing not yet been ported to Visual Studio 2012. The programming module is easy to work with. Designers are installed into Visual Studio so that you get a visual display of the modules and how they are connected to each other. image You also get full Intellisense for the modules as you code and the best part is that you get to interactively debug through the Visual Studio IDE. In the reference assemblies, you can see a set of assemblies that start with “Microsoft.Spot”. The NETMF came out of the SPOT initiative. SPOT was the underlying technology used in a line of “smartwatches” and selected GPS receivers. The “Spot” assemblies make up the core of the NETMF and the Gadgeteer assemblies provide the “glue” between NETMF and Visual Studio. Also, the GHIElectronics assemblies provide the support for the GHI Gadgeteer modules. Determining your camera’s remote shutter circuits You will need a camera that has the ability to use a wired shutter release cable. Most DSLRs and a few point ‘n shoot cameras have a connector for a remote. The camera that I used for this project, a Panasonic Lumix FZ-30, falls in that category. You’ll also need to determine how your camera’s remote is wired. There is a great resource at http://www.doc-diy.net/photo/remote_pinout/ that lists the circuits and connectors for many popular camera makers. Most of them use two wires, one to control the focus, the other to trip the shutter. My Lumix uses a single wire and controls the focus and shutter by changing the resistance over the wire. The hardest part here is getting the connector. I bought a generic Lumix wired remote online for a few dollars and then disassembled it to use the wiring and plug for this project. Hardware list PartDescriptionCost FEZ Ceberus Basic Kit This is a Gadgeteer starter kit that comes with the mainboard, plus some modules. You get a FEZ Cerebus mainboard with a 168Mhz 32bit Cortex M4 processor with floating point, 1MB FLASH and 192KB RAM. Also included are a USB module to supply power and provide a USB connection to the PC, a LED module for blinkenlichten support, and a joystick module. $50 Extender Module Used as a breakout board for the camera and servo pins. $5 10 pin Header block Soldered to the extender module to make it a breakout board. $1 4 pin header block Soldered to camera control board to control focus and shutter. $1 Crimp pins Used to make custom jumper wires for easy assembly. $8 Bluetooth Module Provides access to Bluetooth using the SPP serial profile. $40 USB Portable Charger Provides power to the mainboard and servo motor. Needs to have a mini USB connector. $20 Generic Camera Shutter Release cable For around $7, I was able to get a generic shutter release cable for my camera. It provides the cable needed and a verification of the necessary wiring. $10 2N222 NPN transistors Used to allow the device to open and close the focus and shutter connections. Two are needed. $4 Resistors The combination of resistors that tell the camera what action was requested. Three are needed for the Panasonic Lumix camera that I used. $15 Mini circuit board Small circuit board to hold resistors, transistors, and header block. $8 Wood Two pieces of ¼” thick board. The bottom piece is 6” square. The top is 10” by 6”. $5 Lazy Susan Turntable A ball bearing turntable that allows the top part of the base to rotate around the bottom. This allows the top to rotate around the bottom freely. Available from most hardware stores. Get the one that is 6” square. $10 Futaba Servo Parallax (Futaba) Continuous Rotation Servo to rotate the camera a full 360 degrees in either direction $16 Brad Hole Tee Nut Size: 1/4-20 x 5/16. Creates the tripod socket to allow the Pano Head to be mounted to a standard tripod. Place a section of the yardstick over the tee nut to make it flush mounted. $3 Reduction gears Convert the high speed/low torque rotation from the servo, to a higher torque/lower speed on the camera head. I used part # RHA32-26-60. $8 Servo gear Replaces the standard horn on the servo with a gear that will drive the reduction gear. I used a RSA32-2FS-20 from Servo City. $5 Electrical boxes Cheap and easy way to mount the components. $5 yardstick Chopped up as used for the assembly. $1 Thumbscrew Used to mount the camera to the pano head. The size is ¼”-20 x 1/5”. $1 Wires 22 – 26 gauge. $8 Screws, nuts, and bolts Various screws, bolts, washers to mount everything. $10 Liquid electrical tape Used on the soldered wire connections. $6   Total $240 Getting started with the FEZ Cerebus GHI has a detailed tutorial for getting up and running on the FEZ Cerebus Mainboard. If you are new to the Gadgeteer world, start with the FEZ Cerebus Basic Kit Guide on the Cerebus download page. After installing the compiler and SDK bits, you’ll want to make sure that the board has the correct firmware on it. Detailed instructions on loading the firmware are on the TinyCLR wiki. I recommend using the tutorial to make sure that everything works before moving on. Once we have the compiler and SDK bits installed along with the tutorial compiles and runs, it’s time to start building this thing. Building the camera control board The first part that I assembled was the mini-circuit board for the camera shutter control. I used a single wire to control the focus and the shutter—changing the resistance triggers the camera. So we need to short the circuit between the resistors to get the camera to focus and take a picture. We also want to isolate the circuit from the power coming from the Gadgeteer board. The camera supplies its own power to the circuit and the last thing we want to do is to fry our camera. Accordingly, we’ll use a pair of 2N222 NPN bipolar junction transistors—they are cheap; I bought a bag of 15 from RadioShack for about $3.50—and we’ll use general-purpose input/outputs (GPIO) pins from the Gadgeteer board to toggle the transistors. This is the circuit that I used for my camera: image The jack is part of the cable that I took from the generic wired remote. Having a wired remote that you can take apart will make this project much easier. You can buy just the jack, but there really isn’t much of a difference in price and it’s easy to match up the wires and resistors after you disassemble the remote. When the transistors are turned off, the camera shutter circuit flows through all three resistors and the combined resistance is below the threshold that triggers the camera. When we turn on the focus transistor, the combined resistance drops from 41.1kΩ to 5.1 kΩ. That gets the camera’s attention and puts it in focus mode. Then, turning on the shutter transistor, the resistance drops to 2.2kΩ and the camera takes the picture. You can test this circuit out with a breadboard and use jumpers instead of the transistors. If you can’t find exact matches for the resistors, try to get as close as possible. I was able to use 2k instead of 2.2k and the circuit still worked. For Canon and Nikon DSLR cameras, the circuitry will be much simpler. Instead of using three resistors on one circuit, you will have separate circuits for focus and shutter, though the two will share a common ground. A Canon circuit might look like this: image I soldered the components to a small circuit board and used short jumper wires to connect the 3 lines from the header block to the Gadgeteer extension block. If I ever decide to use this with a different brand of camera, I can make a new board to match that circuit and connect it to Gadgeteer. The red and black wires coming off to the left of the circuit board are connected to the positive and negative wires from the remote cable. The two red wires on the right side of the circuit board are connected to the GPIO pins (pins 3 & 4) on the extender module, and the black wire goes to ground (pin 10) on the extender. Also shown are the lines for the servo motor. Red going to the 5v line on pin 2 of the extender, green to the PWM line (pin 7), and ground is shared with the circuit board on the ground pin. Building the extension block Use a GHI extender module to provide access to power, pulse, GPIO, and ground pins from the mainboard. As shipped by GHI, it looks like this: image For ease of assembly and testing, I soldered a 10 pin header block to the board. In the Gadgeteer library, the pins are numbered from 1 to 10. For the camera control, we’ll be using pins 3, 4, and 10. On the mainboard, I connected this module to socket 5. Each socket on a mainboard has a unique number to identify it, and one or more letters to list the socket capabilities. Each socket can have different electrical and communications capabilities for its pins. Some types support Ethernet signals, others provide the control lines for an SD card controller. When you pick out a Gagdeteer module, it will list the socket type requirements. For example, the Bluetooth module requires a socket with type “U” capabilities. Type U provides UART serial port support with pins 4 and 5 used for sending and receiving data. On the FEZ Cerebus mainboard, sockets 2 and 6 provide type U support. Socket 5 on a FEZ Cerebus has the following types: P, C, and S. The socket type definitions can be found on Gadgeteer CodePlex wiki. The P type includes pulse-width modulated (PWM) outputs on pins 7, 8, and 9, and we need a PWM output to control the server motor. The S type has pins 3, 4, 5 set as general-purpose input/outputs (GPIO) and we need 2 of them to control the camera. The camera control and the servo share pin 10, which is the ground line. Pin 2 provides 5v of power and will be used to power the servo motor. Connect each module to the mainboard to the following sockets: Power Socket 8 Joystick Socket 3 Extender Socket 5 Bluetooth Socket 6 LED Socket 7   Usually when you work with a Gadgeteer module, you drag the mainboard and modules from the toolbox onto the designer. Then you use the mouse to connect the mainboard to the module by dragging from one socket to another. The designer does some code-behind magic and brings in the appropriate reference libraries for each module and then you’re able to start working with the modules. We will do this with the Joystick, Extender, and LED modules. For the Bluetooth module, we will use an open source driver written by Eduardo Velloso. I downloaded the file Bluetooth.cs from Eduardo’s Codeplex site and added it to the project. Connect the focus line from the camera control to pin 3 of the extender module. The shutter line goes to pin 4 of the extender and ground to pin 10. I made up a set of wires with jumper pins on each end to make it easy to connect the modules and soldered the crimp pins to sections of wire to make my jumper cables. Also, I used liquid electrical tape over the solder connections, which made the connections more secure and reduced the chances that wires in adjacent sockets would touch each other. Completed, I would wire up the camera board and servo motor to the extender module with the following arrangement: Device wiresGadgeteer Extender Module Camera Focus Pin 3 (GPIO) Camera Shutter Pin 4 (GPIO) Camera Ground Pin 10 (shared with Servo Ground) Servo power Pin 2 (5v) Servo PWM Pin 7 (PWM) Servo Ground Pin 10 (shared with Camera Ground) Servo motor For the servo motor, we are using a Parallax (Futaba) Continuous Rotation Servo. This is a servo motor that has been modified to allow a full and continuous 360 degree rotation. We need to connect three lines to the servo: power, ground, and pulse-width modulation (PWM). The PWM signal will determine the direction and rate the Servo turns. When the servo receives a 1.5 ms high pulse, the server will be at center position. Speed and direction are controlled by the length of the pulse, which can range from 1.3 ms to 1.7 ms. For correct operation, the servo needs a 20 ms pause between pulses. The Gadgeteer SDK provides the PWMOutput class that allows us to define the PWM parameters. The SetPulse() method takes two parameters, period and hightime, which correspond to the pause and high pulse. These values are specified in nanoseconds (ns). To connect the Servo wiring, connect the power line to pin 2 of the extender module and the ground line to pin 10. I ended up splicing a ground cable as a “Y” cable so that the ground from the extender module could be shared between the camera board and the servo. The white wire coming from the servo is the control line. That gets connected to extender pin 7: The white wire from the servo goes to the green wire jumper wire and connects to pin 7, which is mapped as PWM pin. The red wire goes to pin 2, which provides 5v. The black wire goes to pin 10, which is ground. The camera circuit is not connected here, which makes it easier to see how the servo was wired up. Gadgeteer App With the Gadgeteer hardware assembled, it’s time to get the code working. You’ll want to get the source code from the CodePlex site–everything is built and we can review the highlights here. In ShutterControl.cs, we have the code that will tell the camera to take a picture. We have a class called ShutterControl, which descends from Gadgeteer.Modules.Module. The constructor looks like this: public ShutterControl(int socketNumber) { // Get the Gadgeteet Socket for the specified socket number _socket = Socket.GetSocket(socketNumber, true, this, null); // Define two GPIO pins and set their initial state to false _focus = new DigitalOutput(_socket, Socket.Pin.Three, false, this); _shutter = new DigitalOutput(_socket, Socket.Pin.Four, false, this); } This is where we wire up the pins to the code. We can turn on or off a GPIO pin by calling the Write method of the pin and passing true or false to set the state, and we can implement a method for taking a picture with the following code: public void TakePicture(int shutterTime) { // Tell the camera to focus SetFocus(true); // wait 1/10 of a second Thread.Sleep(100); // Tell the camera to open the shutter SetShutter(true); // Hold the shutter open for the specified time if (shutterTime > 0) { Thread.Sleep(shutterTime); } // Let go of the shutter SetShutter(false); // let go of the focus SetFocus(false); } The main execution block is in the Program partial class, Program.cs. Create an instance of ShutterControl with the following code: ShutterControl shutterControl = new ShutterControl(5); That gives a ShutterControl object bound to socket 5. Then, taking a picture is as simple as calling: shutterControl.TakePicture(1000); Bluetooth (on the Gadgeteer side) So why Bluetooth when all the cool kids are using Wi-Fi? There are a couple of reasons: • It’s cheaper. The Bluetooth Gadgeteer module is half the cost of the cheapest Wi-Fi module. • It uses less power. There’s no point in draining your phone’s battery any faster than you have to. • It’s much, much easier to configure. At the time of this writing, you cannot make the Gadgeteer the host in an Adhoc Wi-Fi network. That means it has to connect to an existing network. This opens up a box filled with ugly things. For example, there is neither a display nor a keyboard for this device, and so the user has no way of selecting a Wi-Fi network to join or entering a WEP or WPA key. The Gadgeteer Bluetooth module supports the Serial Port Profile (SPP). Basically, it’s treated like a modem. When the app starts up, we call an InitBluetooth() method: void InitBluetooth() { // Keep a quick reference to the Bluetooth client, to make it // easier to send commands back over the module client = bluetooth.ClientMode; // Set the Bluetooth device name to make it easier to identify when // you pair this module with your phone bluetooth.SetDeviceName("Coding4Fun Pano Head"); // We want to track when we are connected and disconnected bluetooth.BluetoothStateChanged += new Bluetooth.BluetoothStateChangedHandler(bluetooth_BluetoothStateChanged); // We want to collect all the data coming in bluetooth.DataReceived += new Bluetooth.DataReceivedHandler(bluetooth_DataReceived); }   Command Parser A simple command parser is implemented in CommandParser.cs. All of the data that comes in from the Bluetooth module gets appended to a custom Queue() class defined in CommandQueue.cs. A background thread calls the parser, which looks for command strings. Every command string starts with the “@” character and ends with a “#” character. The CommandParser.parse() goes through the buffer and queues up commands in the order they came in. The commands recognized by the app are defined as string constants in commands.cs. The CheckForCommands() method is called after parsing the data and takes action for each command that comes in: private void CheckForCommands() { if (_commandParser.Commands.Count > 0) { ControlCommand controlCommand = _commandParser.Commands.Dequeue(); switch (controlCommand.Action) { case Commands.CMD_LEDS: SpinLights(); _client.Send("OK"); break; case Commands.CMD_VERS: SendVersion(); break; case Commands.CMD_STOP: _haltRequested = true; _servoControl.Stop(); break; case Commands.CMD_RIGHT: _servoControl.ClockWise(_servoControl.Speed); break; case Commands.CMD_LEFT: _servoControl.ClockWise(-_servoControl.Speed); break; case Commands.CMD_SHUT: _shutterControl.TakePicture(); break; case Commands.CMD_PANO: var p = new PanoSettings(); p.Load(controlCommand.Params); PanoramaOperation(p); break; } } }   To take a picture, the sender sends the start of command character, “@”, following by the CMD_SHUT string, and finally the end of command character, “#”. As a single string, it‘s “@SHUT#”. Joystick processing The joystick that comes with the kit has a button click event and you can poll it for the current position. I used the command sequence of a double click, followed by a direction. Double-click and up will put the Bluetooth module into pairing mode so that your phone can be paired to the device. A second double-click and up will reset the Bluetooth module to cancel pairing mode. Double-click and either left or right will rotate in that direction until the joystick is moved to another position. Double-click and down will put the servo into calibrate mode until the direction changes. The sequence is to double-click the joystick, then pick a direction. I coded the following functions: Joystick Up: Puts the Bluetooth module into pairing mode. You need to do this once with the phone, to pair the phone with the device. Double-click, then Up will cancel pairing mode. Joystick Left: Tells the servo to rotate left at the default speed. Continues until joystick changes direction. Joystick Right: Tells the servo to rotate right at the default speed. Continues until joystick changes direction. Joystick Down: Sends the 0 rotation signal to servo to allow you to set the set point of the servo. This is how you will calibrate the servo. Continues until joystick changes direction. private void CheckJoyStick() { if (_joyStickCommand.CheckState() == JoyStickCommandState.DoubleClicked) { var direction = _joyStickCommand.GetDirection(joystick.GetJoystickPosition()); switch (direction) { case JoyStickDirection.Right: _servoControl.ClockWise(_servoControl.Speed); // turn to the right until the joystick is moved to a different direction while (direction == JoyStickDirection.Right) { Thread.Sleep(300); direction = _joyStickCommand.GetDirection(joystick.GetJoystickPosition()); } _servoControl.Stop(); break; case JoyStickDirection.Left: _servoControl.ClockWise(-_servoControl.Speed); // turn to the right until the joystick is moved to a different direction while (direction == JoyStickDirection.Left) { Thread.Sleep(300); direction = _joyStickCommand.GetDirection(joystick.GetJoystickPosition()); } _servoControl.Stop(); break; case JoyStickDirection.Up: if (!_inPairingMode) { _client.EnterPairingMode(); } else { _bluetooth.Reset(); } _inPairingMode = !_inPairingMode; break; case JoyStickDirection.Down: _servoControl.Calibrate(); while (direction == JoyStickDirection.Down) { Thread.Sleep(300); direction = _joyStickCommand.GetDirection(joystick.GetJoystickPosition()); } _servoControl.Stop(); break; } if (direction != JoyStickDirection.None) { _joyStickCommand.ClearState(); } } }   Calibrating the servo You can use the screwdriver included in the Parallax kit to turn the adjustment potentiometer on the servo. Put the device into calibrate mode via the joystick. Then, slowly turn the potentiometer in one direction. If the servo slows down, keep turning in that direction until the servo stops. If the servo starts going faster, then turn the potentiometer the opposite direction until the servo stops turning. If you turn the potentiometer past the zero point, the servo will start to spin in the opposite direction. If this happens, just turn the potentiometer very slowly in the other direction; it may take several tries to get it just right. While writing this code, I managed to brick the board. I wrote some code to calibrate the servo and it used a while forever loop that was called when the device restarted. This eventually threw an error and prevented me from updating the app. I was forced to wipe the firmware and start from scratch. For the FEZ Cerberus board, the instructions are here: http://wiki.tinyclr.com/index.php?title=Firmware_Update_FEZ_Cerberus Building the pano head   Cut two pieces of wood. The bottom piece is sized to match the Lazy Susan swivel, which is 6” square. Measure and mark the center of this board on both the top and bottom sides. Attach the bottom of the Lazy Susan to the top side of the bottom piece. Then, mount the larger reduction gear to the center of the top side of the bottom board: image Mount a tripod socket to the center of the bottom side of the board: image Mount the smaller reduction gear to the servo motor. This will replace the horn that comes with the servo: image Cut the top piece. This will be a little larger—I made a 10” by 7” rectangle. Drill the holes to mount it to the swivel and then mount the swivel just long enough to mark its center. Make sure that the two boards spin freely with the swivel unit. The first swivel that I used would bind up after 270 degrees of rotation. A replacement unit spun freely. Next, cut a rectangular opening of about 1” by 3” in the top of the board, with one end over the center of swivel. This will allow the servo to be positioned in the hole so that the gears match up. Secure the top board to the swivel unit: image Position the servo so that its gear is flush against the reduction gear. Getting the correct fit is important in order for the pano head to reliably turn. I used metal mounting strips from the hardware store and was able to secure the servo with two sets on either end sandwiching the servo mounts: image Now we have to mount the Gadgeteer parts and provide a camera mount. I took the low road here and picked up a pair of PVC wall boxes for electrical outlets from the hardware store. I placed them on opposite sides of the servo, secured the various Gadgeteer modules to one box, and left the other one open to hold the battery back. For ease of assembly, the extender module was not yet connected: image image image Connect the jumper wires to the camera shutter board and extender module and connect the jumpers to the servo connectors. The camera board will connect the following lines to the extender module: Pin 1 (shutter) Pin3 (GPIO) Pin 2 (focus) Pin 4 (GPIO) Pin 4 (ground) Pin 10 (GRD) The servo will connect the following lines to the extender module: Positive (red) Pin 2 (5v) Control (white) Pin 7 (PWM) Ground (black) Pin 10 (GRND) The ground line of the extender module is shared between the camera control and the servo. Connect the extender module to socket 5 of the Cereberus mainboard.   For the camera mount, I took the low road again and cut a section from a yard stick to bridge the tops of the electrical boxes. In the center, I drilled ¼” hole and put a ½” thumbscrew to fit the tripod mount. At this point, you can use the joystick to test various functions of the hardware. Make sure that everything works before you tackle the Bluetooth remote control: image   Windows Phone 8 App Now that the Pano Head has been built, we need the remote control—a Windows Phone 8 device, I used my HTC 8X, but any WP8 device should work. As regards the compiler, we need to switch gears. While the Gadgeteer library required Visual Studio 2010, you need Visual Studio 2012 and Windows 8 for Windows Phone 8 development. Windows 8 Pro is required for the Windows Phone emulator, but that is moot in this case. Since you can’t emulate Bluetooth connectivity in the emulator, you’ll need to have an actual WP8 phone. I used the Windows Phone Pivot App template, but ended up ditching the pivot control as the app really only has a single page. To use Bluetooth, I need to add the ID_CAP_PROXIMITY and ID_CAP_NETWORKING capabilities to the app manifest. The completed app has two pivot pages and they look like this: image The Settings page, showing the various controls About the icons in the apps The app bar icons were generated with Syncfusion’s Metro Studio 2. Metro Studio 2 contains a collection of 1700 “Metro” style icon templates that be used to create customized icons for Windows Store Apps and Windows Phone Apps. Metro Studio 2 is a free gift from Syncfusion and the icons provided are royalty free without any usage restrictions. The app icon that appears on the phone was derived from a camera image from the Open Clipart Library. The image that I used was a basic camera on a tripod image that works well with Windows Store and Windows Phone Store designs: image  Using the app The panoramic setup takes 5 controls: Turn time How long to run the servo motor to make the turn. Settle time How long to wait after turning before taking the picture. Pause time How long to wait after taking the picture before turning again. Iterations How many times to turn. Go! Send the command to the Pano Head to start taking panoramic pictures.   The times are measured in milliseconds. The app bar has two modes: connected and disconnected. When disconnected, the only button available is the connect button. All other controls are disabled until a connection is made. When there is a connection, 4 buttons and a menu option appear on the app bar: Take picture How long to run the servo motor to make the turn. Turn left Turn the Pano Head in a counter-clockwise direction until the stop button is pressed. Stop Tells the servo motor to stop turning. Turn Right Turn the Pano Head in a clockwise direction until the stop button is pressed. Disconnect Clear the Bluetooth connection to the Pano Head.   The IntegerTextBox custom control The panoramic setting controls use sliders and text boxes to change the settings. We are following a MVVM pattern and the sliders and text boxes are bound to view mode properties. When you change a slider, the associated text box is updated and vice versa. For the text boxes, I made them accept only integer inputs. I also made them right-aligned, as that is what most people expect for numeric input controls. To make the process easier, I created a new IntegerTextBox class based on the standard TextBox. I created a Windows Phone Class Library with just the IntegerTextBox class. Basically, I made three changes to the behavior of the TextBox. The popup keyboard is set to the Digits keyboard, TextAlignment is set to TextAlignment.Right, and OnKeyDown is overridden in order to only allow the digit keys and the backspace key. It all comes out like this: public class IntegerTextBox: TextBox { private readonly Key[] _num = new Key[] {Key.Back, Key.D0, Key.D1, Key.D2, Key.D3, Key.D4, Key.D5, Key.D6, Key.D7, Key.D8, Key.D9 }; public IntegerTextBox() { InputScope = new InputScope(); InputScope.Names.Add(new InputScopeName { NameValue = InputScopeNameValue.Digits }); TextAlignment = System.Windows.TextAlignment.Right; } protected override void OnKeyDown(KeyEventArgs e) { if (Array.IndexOf(_num, e.Key) == -1) { e.Handled = true; } base.OnKeyDown(e); } } Once the custom control project compiles, add that project as a reference to the phone project. Then add the namespace to the MainPage.xaml so that you can use the new control: <phone:PhoneApplicationPage xmlns:PhoneControls="clr-namespace:Coding4Fun.PhoneControls;assembly=Coding4Fun.PhoneControls" x:Class="Coding4Fun.PanoHead.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> Settings Settings are persisted to IsolatedStorageSettings.ApplicationSettings. I used the sample code posted on MSDN, “How to create a settings page for Windows Phone”, to create a class with accessor functions in order for all of the properties to persist. Hurray for Bluetooth Microsoft greatly enhanced the API access to the Bluetooth hardware with Windows Phone 8, extending the Windows 8 StreamSocket and Peerfinder APIs to include Bluetooth. With this, you get TCP-style socket level programming over Bluetooth. At first glance, it would appear that the lack of a SPP API would make it difficult to have a WP8 device talk to the Pano Head. It turns out that’s not the case—we can use a socket connection from the phone to send and receive data from the Pano Head. The PeerFinder class was designed to allow Windows Store apps to discover other instances of the app on other devices. But it can also be used to locate other devices once they have been paired to your phone. The way to do this is to add “Bluetooth:PAIRED” to the PeerFinder.AlternateIdentities list. That tells PeerFinder to include the list of already paired devices when searching for matching apps. We can then find the Pano Head in the list of paired devices: private async Task<HostName> QueryForHost() { // Tell PeerFinder to only enumerate paired devices // See http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj207007(v=vs.105).aspx#BKMK_Codeexamples PeerFinder.AlternateIdentities["Bluetooth:PAIRED"] = ""; IReadOnlyList<PeerInformation> devices = null; try { // Get a list of matching devices devices = await PeerFinder.FindAllPeersAsync(); } catch{} // If we can't find any devices, goto to the phone's Bluetooth settings if (devices == null || devices.Count == 0) { MessageBox.Show(AppResources.NoBlueToothDevices); await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:")); return null; } // Find the first device that identifies as the Pano Head, otherwise go to the Bluetooth settings PeerInformation peerInfo = devices.FirstOrDefault(c => c.DisplayName.Contains("Pano Head")); if (peerInfo == null) { MessageBox.Show(AppResources.NoPairedPanos); await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:")); return null; } // Store the device name so the next connection attempt will use that first saveString("lastdevice", peerInfo.HostName.RawName); // Return the hostname return peerInfo.HostName; }   Once we find the Pano Head, we open a StreamSocket connection to the device. The Pano Head sees it as an SPP connection on its side, while on the phone-side it’s TCP -style socket coding. Once we have established the connection, it’s a straight forward task to send commands from the phone to the Pano Head. The socket code is wrapped up inside a PanoControl class. We create an instance of a DataWriter on the socket’s OutputStream, and to send a command to the Pano Head we just have to write a string using the DataWriter’s WriteString method. For example, to tell the Pano Head to take a picture, implement a TakePicture() method like so: public async Task TakePicture() { await SendCommand(Commands.CmdShut); } public DataWriterStoreOperation SendCommand(string command) { CheckForDevice(); _dataWriter.WriteString(String.Format("@{0}#", command)); return _dataWriter.StoreAsync(); }   Though we use the same string constant file from the Gadgeteer project, that’s pretty much the only code shared between the two projects. Using the Pano Head Taking the pictures is just a matter of finding the right location—one with the sun overhead and a stable location for the tripod. Since you are shooting a full 360 degrees, if the sun is lower in the sky, the camera will at some point be aimed at it and it will blow out the image. Once you have the camera in the right spot, it’s time to try a few panoramic shots. You want to have overlapping shots, and I found that 16 pictures taken at 20-degree intervals worked for my camera. You’ll have to experiment a bit with the turn time setting to get that 20 degree turn. Remember to allow a couple of seconds for the settle and pause times, giving the Pano Head enough time to settle after turning as well as enough time for your camera to focus and take the picture. There are various ways of stitching multiple images together to make up a panoramic picture. Microsoft has excellent tool with their Photosynth app and site. You can create a panoramic picture with their desktop app and upload to their site for free hosting. You will need two desktop apps, the Image Composite Editor (ICE) and Photosynth. ICE is the application that will stitch the Images together into a panorama and Photosynth will publish the panorama to the Photosynth site. Register an account on the Photosynth site and download the two applications here. Creating a panoramic picture using Photosynth 1. Take the pictures. You want some overlap, which will make it easier to stitch the images together. 2. Copy the pictures to your computer. 3. Launch Photosynth. If launched for the first time, the app will ask for Windows Live ID. Use the same account that you registered with on the Photosynth site. Once it comes up, you can ignore it. 4. Launch ICE. 5. Load your images into ICE. ICE will immediately start compositing the images. If you do not have sufficient overlap with the images, ICE will not be able to use all of the images. 6. Click the “Publish to Web…” button. ICE will generate the panorama and use Photosynth to upload the image. 7. Fill out the details when the “Upload Panorama” dialog appears and click the “Upload” button. 8. Photosynth will upload the panorama. When it’s complete, click the “view” on the Photosynth window. My Sample I tested the Pano Head at a local nature preserve. After some trial and error, I took a series of 16 pictures that yielded a full 360-degree view. I copied the pictures from my camera to my PC and loaded them into ICE. Here are the results: image Conclusion This project was a lot of fun to build. Since I had never soldered anything before, it helped me develop a new skill set. I went to RadioShack and bought some components and a small circuit board to practice on. While it is possible to learn how to solder via YouTube and Twitter, it was tough going at first: image I had a lot of trouble getting the solder to stick to the board on my first attempt. It was a facepalm moment. Needless to say, I did get a bit better at soldering. This was also my first Windows Phone 8 project. It was very easy to write for and a breeze to debug. After doing some work on other mobile platforms, I felt much more productive with Windows Phone 8. If you want to try this out, the download link for the source code is at the top of the article! About The Author Chris Miller is a senior R&D engineer for Tyler Technologies, working on the next generation of school bus routing software. He is also the leader of the Tech Valley .NET Users Group (TVUG). You can follow Chris at @anotherlab and check out his blog at anotherlab.rajapet.net. Chris started out with a VIC-20 and been slowly moving up the CPU food chain ever since. ]]> https://channel9.msdn.com/coding4fun/articles/Pano-Head The Pano Head is a rotating platform for a camera that mounts on a tripod and is controlled from your Windows Phone 8 device over Bluetooth. You can use it to take a series of pictures that you can stitch up with Photosynth. I’ve always wanted to take panoramic pictures with my camera from a tripod, so I decided to make a remote controlled panoramic tripod head that would screw on to any tripod. Using a motor and a shutter control, a series of pictures can be taken. With the use of Photosynth, those pictures can be stitched up to make an interactive 360-degree view. You can also use your Windows Phone 8 as a remote shutter release over a Bluetooth connection. Windows Phone 8 has a Bluetooth API that allows us to program connectivity using TCP/IP style sockets. This is a popular project in the Arduino world and I wanted to complete it using Gadgeteer hardware and the .NET Micro Framework (NETMF). This project uses the FEZ Cereberus mainboard module, but you should be able to use other Gadgeteer mainboards without any problems. What is the .NET Gadgeteer platform?The .NET Gadgeteer platform is an open source toolkit for building small electronic projects using Gadgeteer hardware modules and programmed using the .NET Micro Framework with Visual Studio 2010 or Visual C# Express (2010 edition). The Gadgeteer modules connect together using special cables and very little soldering is required. You typically use a mainboard module, which has the CPU and memory, and then connect various modules (camera, sensors, networking, display, controllers, etc) to accomplish your chosen task. This part is going to require Visual Studio 2010 C#. Whether the full version or the Express version, it has to be 2010. This is because the Gadgeteer libraries have as of this writing not yet been ported to Visual Studio 2012. The programming module is easy to work with. Designers are installed into Visual Studio so that you get a visual display of the modules and how they are connected to each o https://channel9.msdn.com/coding4fun/articles/Pano-Head Thu, 07 Mar 2013 18:00:00 GMT https://channel9.msdn.com/coding4fun/articles/Pano-Head Chris Miller Chris Miller 0 https://channel9.msdn.com/coding4fun/articles/Pano-Head/RSS Flying the AR.Drone 2.0 with Windows Store Applications The AR.Drone 2.0 The Parrot AR.Drone 2.0 is an awesome device packed with cool features. The drone contains two cameras, one pointed forward that streams live video, and one pointed downwards (for all your surveillance needs). Its got four powerful engines that make it fast and maneuverable. The drone’s firmware keeps it stable and level while stationary or performing maneuvers, handling a huge burden for the user. It’s a fun device to write code for, and even more fun to pilot when you’re done! There’s a few projects that have created AR.Drone APIs that can be used for Windows 8 Desktop Apps. However, I wanted to fly my drone from a Windows Store App, so I decided to build my own API compatible with WinRT. The result is covered in this series of posts. Thanks to Nisha Singh (http://blogs.msdn.com/b/nishasingh/) and everyone else who helped me out with this project! In the first post, I’ll go over how the API handles communicating with and controlling the drone, and then demonstrate how to use the API to make a simple control App.   API Information and Terms The API consists of 5 files: • DroneConnection.cs: functionality to connect to, and disconnect from, the drone. • DroneControl.cs: contains the control loop. • DroneMovement.cs: contains methods that construct and return fully-formatted commands. • InputProcessing.cs: determines the next command to issue to the drone. • InputState.cs: used to pass information between the UI and back-end. • The terms the API code uses to refer to axes of movement are as follows: • DroneStrafeX: left-right. • DroneStrafeY: forward-backward. • DroneRotateX: yaw, or rotation. • DroneAscendY: up-down. •   Communicating with the Drone The AR.Drone 2.0 communicates with other devices through its own wireless network. Sending the drone instructions is as simple as connecting your computer to the drone’s network, opening a UDP connection to the drone (I.P. 192.168.1.1, Port 5556), and then sending commands over this connection. The code to connect to the drone is contained inside DroneConnection.cs: // Initialize the connection to the drone public static async Task ConnectToDrone() { ... // Set up the UDP connection string remotePort = "5556"; HostName droneIP = new HostName("192.168.1.1"); udpSocket = new DatagramSocket(); await udpSocket.BindServiceNameAsync(remotePort); await udpSocket.ConnectAsync(droneIP, remotePort); udpWriter = new DataWriter(udpSocket.OutputStream); ... }   Once a connection has been established, we can begin to send the drone messages: // Send a command to the drone public static async Task SendDroneCommand(string command) { udpWriter.WriteString(command); await udpWriter.StoreAsync(); } This networking code is discussed more in-depth here: Try, Catch, Finally... - UDP and Windows 8 Apps The drone needs to continuously receive commands for it to remain responsive. If the drone doesn’t receive any commands for two seconds, it assumes the connection has been lost, and it will ignore any further commands. If this happens, you need to close and re-establish the connection before you can continue to pilot the drone. DroneConnection.cs contains methods that allow you to do this.   Commanding the Drone You can command the drone by sending it strings called AT commands. There are seven different categories of AT commands, but only two are required to fly the drone, and are the only ones included in the API: • AT*REF – Used for basic behavior such as takeoff/landing, and emergency stop/reset. • AT*PCMD – Used to fly the drone once airborne. This controls pitch, yaw, roll, and altitude. • AT commands have very specific formatting, and consist of four parts. An improperly formatted command will be ignored by the drone. The different sections of an AT*PCMD command are highlighted below:   AT*PCMD=23,1,0,0,0,0\r\n   Header: The type of the AT command Sequence Number: The sequence number is used by the drone to keep track of which commands it needs to execute. The drone will not execute any commands with a sequence number lower than the highest sequence number it has received so far. The first command sent should always have a sequence number of 1, and each command sent subsequently should increment this number by 1. The sequence number can be manually reset by sending a command with the number 1. Payload: This carries the command arguments. Its format and content vary from command to command. In the AT*PCMD command, the first value is a flag indicating whether the drone should do nothing (low) or move according to the other arguments (high). The next four values denote roll, pitch, vertical speed, and angular speed respectively. These values are floats ranging from [-1, 1], where (0, 1] represents movement speed in one direction, and [-1, 0) represents the other. A 0 causes the drone to remain stationary along that axis, a 1 or –1 is maximum movement speed in their respective directions, and each value between is a fraction of the maximum possible speed. For example, in the pitch argument, a .75 would cause the drone to move backward at 3/4 maximum speed, while a –.5 would make it move forward at 1/2 the possible speed. However, the drone doesn’t respond to values in the [-1, 1] range. The actual value that needs to be inserted into the AT command is the signed integer value represented by the bytes the float is actually stored in. This conversion is done for you in the FloatConversion method in DroneMovement.cs. Carriage Character: A newline character. Use the one specific to your environment. DroneMovement.cs has a set of methods to generate AT*REF and AT*PCMD commands, all of which take the current sequence number as an argument, and return a ready-to-send AT command. Some methods take additional arguments to control the movement speed. An example of one of these methods is: // Strafe drone forward or backward at velocity in range [-1,1] public static string GetDroneStrafeForwardBackward(uint sequenceNumber, double velocity) { // Convert the ratio into a value the drone understands int value = FloatConversion(velocity); return CreateATPCMDCommand(sequenceNumber, "0," + value + ",0,0"); } // Return a full ATPCMD command private static string CreateATPCMDCommand(uint sequenceNumber, string command) { return "AT*PCMD=" + sequenceNumber + ",1," + command + Environment.NewLine; } Control Infrastructure The drone is controlled with an continuous loop that sends a command to the drone every 30 ms. Each cycle, the loop determines the next command, sends the command to the drone, and then increments the sequence number. The method is asynchronous and awaits the call to System.Threading.Tasks.Task.Delay() so that it doesn’t block the UI between cycles. public static async void ControlLoop() { while (true) { ... // Get and send the next command string commandToSend = InputProcessing.NextCommand(sequenceNumber); await DroneConnection.SendDroneCommand(commandToSend); sequenceNumber++; await System.Threading.Tasks.Task.Delay(30); } } You need to implement the InputProcessing.NextCommand() method to return an AT command based on criteria of your own choosing. The API includes the class InputState.cs that you can use to pass information between your UI and the control infrastructure. The example App contains an example of this. Example App I’ve included a simple example App to demonstrate how to use the API. The App allows you to connect to the drone and make it take off, land, and rotate. It also illustrates how to pass input information between the UI and the control infrastructure using InputState instances. In the App, FlyingPage contains the method GetState() that returns an instance of InputState. GetState() looks at the input the App is receiving, then creates and returns an instance of InputState containing that information. // returns the current state of the input controls public static InputState GetState() { // slider value is in the range [-1,1] return new InputState(0, 0, 0, sliderValue, isFlying); } InputProcessing.NextCommand() calls GetState, and then interprets the state to decide on the next command to send: // returns the next command that should be executed public static string NextCommand(uint sequenceNumber) { InputState state = MainPage.GetState(); // Determine if the drone needs to take off or land if (state.startFlying && !isFlying) { isFlying = !isFlying; return DroneMovement.GetDroneTakeoff(sequenceNumber); } else if (!state.startFlying && isFlying) { isFlying = !isFlying; return DroneMovement.GetDroneLand(sequenceNumber); } // Check if the drone needs to rotate if (state.rotateX != 0) { return DroneMovement.GetDroneRotate(sequenceNumber, state.rotateX); } // Otherwise have the drone do nothing. return DroneMovement.NullCommand(sequenceNumber); } The command decision is made in order of importance. Takeoff and landing commands are the most important, followed by movement commands. If there is no other command to send, NextCommand() returns a null command so that the drone will continue hovering and listening to the connection. Once NextCommand() has been implemented, all the App needs to do is connect to the drone and initiate the control loop by calling DroneConnection.ConnectToDrone(), followed by calling DroneControl.ControlLoop(). In the example App, this is done in the handler for the connect button. Once the control loop is running, the drone is ready to fly! Get Flying The API should give you everything you need to get started writing drone Apps for Windows Store. In part 2, I’ll discuss a more complete App I’ve written to pilot the drone. There’s still so much drone functionality to be exposed, so get coding and get flying! ]]> https://channel9.msdn.com/coding4fun/articles/Flying-the-ARDrone-20-with-Windows-Store-Applications The AR.Drone 2.0The Parrot AR.Drone 2.0 is an awesome device packed with cool features. The drone contains two cameras, one pointed forward that streams live video, and one pointed downwards (for all your surveillance needs). Its got four powerful engines that make it fast and maneuverable. The drone’s firmware keeps it stable and level while stationary or performing maneuvers, handling a huge burden for the user. It’s a fun device to write code for, and even more fun to pilot when you’re done! There’s a few projects that have created AR.Drone APIs that can be used for Windows 8 Desktop Apps. However, I wanted to fly my drone from a Windows Store App, so I decided to build my own API compatible with WinRT. The result is covered in this series of posts. Thanks to Nisha Singh (http://blogs.msdn.com/b/nishasingh/) and everyone else who helped me out with this project! In the first post, I’ll go over how the API handles communicating with and controlling the drone, and then demonstrate how to use the API to make a simple control App. API Information and TermsThe API consists of 5 files: DroneConnection.cs: functionality to connect to, and disconnect from, the drone. DroneControl.cs: contains the control loop. DroneMovement.cs: contains methods that construct and return fully-formatted commands. InputProcessing.cs: determines the next command to issue to the drone. InputState.cs: used to pass information between the UI and back-end. The terms the API code uses to refer to axes of movement are as follows: DroneStrafeX: left-right. DroneStrafeY: forward-backward. DroneRotateX: yaw, or rotation. DroneAscendY: up-down. Communicating with the DroneThe AR.Drone 2.0 communicates with other devices through its own wireless network. Sending the drone instructions is as simple as connecting your computer to the drone’s network, opening a UDP connection to the drone (I.P. 192.168.1.1, Port 5556), and then sending commands over this connection. The code to connect to the drone i 38 https://channel9.msdn.com/coding4fun/articles/Flying-the-ARDrone-20-with-Windows-Store-Applications Wed, 30 Jan 2013 20:44:13 GMT https://channel9.msdn.com/coding4fun/articles/Flying-the-ARDrone-20-with-Windows-Store-Applications Clint Rutkas, Peter Dwersteg Clint Rutkas, Peter Dwersteg 6 https://channel9.msdn.com/coding4fun/articles/Flying-the-ARDrone-20-with-Windows-Store-Applications/RSS C# Hardware Windows Store App Fall Fury: Part 12 - Conclusions Project Conclusions Developing FallFury was a fun and educational activity. Besides the fact that I got to work with an amazing team of people who were willing to assist me with the testing and development, I learned some important points about the development process as a whole and have outlined them in this article.  Check out the video for this article at https://channel9.msdn.com/Series/FallFury/Part-12-Project-Conclusion.  For a complete, offline version of this series, you may download a nicely formatted PDF of all the articles. Go Outside Your Comfort Zone This past summer, I decided to tackle a new challenge—game development. Never before had I built a game from the ground up. Moreover, as I could already find my way around C# code, I decided that I wanted to make C++ the language of choice, and so worked with DirectX instead of XNA. Additionally, the project needed to be constructed with Windows 8 as the target platform and I’d have to rely on the WinRT stack. The concepts were new to me, but I figured that learning about a new platform and a new language would be more interesting than sticking to my comfort zone. Through FallFury I extended my knowledge about pointers, trigonometry, how DirectX handles a lot of the graphics legwork, and how to write HLSL shaders. It was a challenging but very rewarding experience. Communicate The most important part of any project is communication. There are always people who know more than you in one field or another, so don't hesitate to reach out to other developers and ask questions. Your code is not perfect, so talk about best practices used in production and how you can improve on what you already have—communication should not be limited to your team, floor, or even building. One bonus of my experience at Microsoft was discovering that a lot of developers, when not in a meeting or in the middle of an important assignment, are more than happy to help a fellow employee with a piece of advice or some code review. Plan the Small Details Before you even touch the keyboard to write your first line of code, outline the components of your application and have a general idea of how you’ll implement those components as well as how they’ll interact with each other. It is tempting to start coding and then add or modify features, but doing so will create more problems than it will solve. Build Small Prototypes FallFury is a complex project composed out of blocks such as: • XML level/metadata reader and writer • The Share and Settings charm components • SpriteBatch sub-system • Level renderer • Screen sub-system • Menu interaction sub-system Each block is responsible for its own set of tasks and each can be individually tested with either mocked data or a loose connection to the existing codebase. The necessity for small prototypes comes from individual requirements tied to the platform and possible integration scenarios. For example, when I began development, I created a non-hybrid DirectX project, which meant that if I needed to introduce XAML integration, I had to rewrite small parts of my swap chain preparation stack as well as work with a lot of XAML content in the code-behind. The Settings charm integration heavily relied on XAML, and I would have had to write the popup and control-related code in C#. Obviously, that was not an option, so I created a hybrid project instead and ported most of my code into the new solution. Lesson learned here: prototype—and prototype early—in order to make sure that what you plan to implement will be implemented in an efficient manner. Test Often, Test with Other People When working on an application, it is important to understand the needs and expectations of your target audience, and a big part of this is making sure that the application provides a way for the user to easily learn about an action without a helper booklet. The menu system is a good example of this in FallFury. As I was designing the buttons on my screens, I tried to implement the approach used in games such as Dance Central—the user simply slides the button-panel and it takes him to the screen that was linked to that specific button. However, as I was testing the application with the local development crowd, I noticed a pattern—people were attempting to simply tap the button instead of sliding it. To avoid this confusion, I added a pulsating arrow on the right side of the button in order to highlight the fact that the button should be displaced in order to be activated. The XML level loading system is another example of how secondary testing improved FallFury. Initial element positioning relied on a given level length, as well as on a ration-based placement. For example, if I wanted to put a button in the middle of the screen, I could position it with a value, such as .5. The level loader would then translate this value relative to the screen size. Rick Barraza was creating some test levels when he notified me about a big flaw—as the level extended, some elements were mis-positioned by a large margin compared to the original intended location. This was because when a level length was reset, the ratio was applied on a larger/smaller value, and some elements would therefore overlap. Ultimately, I rewrote the level structure to rely on pixel values, and designed the level-length to calculate automatically based on the included elements and their size. Test on Different Hardware FallFury started with portable hardware in mind. Its original design targeted Windows 8 tablet devices, though it was later decided that the project should support desktop machines as well. That automatically added thousands of possible hardware combinations on which the game might potentially run. Here are just some of the test machines we got to use: • Samsung Series 7 Slate • ARM Developer Tablet (Microsoft Surface) • ASUS EP121 Slate Each of these machines came with its own specific conditions that had to be accommodated. While Samsung Series 7 Slate featured an accelerometer, at the time of development the ASUS EP121 tablet did not have Windows 8 drivers for its sensor. When I sideloaded the game, I noticed that I could no longer control the character the way I wanted to. Also, though FallFury has keyboard controls, I had to develop controls for machines without keyboards. This is why I came up with the concept of touch-based, on-screen controls. Moving on to the ARM device, first and foremost I noticed that my shader configurations were not compatible with the platform capabilities. All my testing was done on a machine that supported DirectX Feature Level 10, which was not the case for a low-power ARM machine that supports DirectX Feature Level 9.1. I had to work with some MSDN samples to find a way to properly modify the required shaders so they would work on Windows RT. ARM devices are built with battery life in mind. Therefore, their capabilities are reduced compared to those of a full-sized Windows tablet. This had an impact on the general game performance—some parts of the game, such as particle rendering, were working fine on a desktop machine, but were quite laggy on the ARM tablet. Knowing the possible source of the problem, I had to optimize the particle storage and rendering stack to ensure they didn’t affect the user experience on Windows RT hardware. There Is Never Enough Time - Learn To Cut When I started planning FallFury, I worked up a huge list of features. As the deadline approached, however, I noticed that I somewhat underestimated the allocated project time—a lot of time was spent on testing and eliminating bugs in existing features. That was the point at which I had to cut my feature set. When designing the feature list for your app, make sure that you have a clear vision of which features get the priority and which can be cut if necessary. For example, FallFury was originally planned to be a multiplayer game. Although it was tempting to start working on it as such from the very beginning, I knew that it wasn’t a core feature and that it wouldn’t necessarily affect the general play experience on release day. Ultimately, multiplayer capability was dropped from initial development along with a number of other not-immediately-integral features. Expect the Unexpected When allocating time for the project, anticipate situations that might derail the process and cause a delay in the planned delivery date. It is easy to estimate that creating an accelerometer-based motion system will take you a day or two, but you also need to allow for the potential possibility of your code not working as expected, hardware accidents, natural disasters, etc. Doing so will help you focus on the right features at the right time while diminishing the risk of missing the deadline. Platform Samples Are the Best Documentation - Learn to Read Others’ Code While building the core of FallFury, I leveraged multiple features that hadn’t yet become mainstream among Windows developers. Therefore, the documentation was scarce and in some instances the only help I could get was internal. Luckily, Microsoft bundled hundreds of samples that demonstrate what the new platform can do. A lot of the development approaches gained during my internship were learned from looking at the official, publicly released sample code. The lesson here: if it's not on MSDN or blogs, check the official developer samples. For example, I used the DirectX sprite drawing sample to see how to build a proper sprite rendering mechanism with behavior similar to the one available in XNA. Atomic Commits When I started, source control wasn’t new to me, but there were proper usage practices that I didn’t apply before the internship. One of them is atomic commits, which I learned from Clint Rutkas. With every new addition to the application, chances are something might go wrong. It could be a faulty third-party assembly, a misplaced class, or a broken reference that brings down the entire solution. If the commits include longer time intervals, for example, you will ultimately have to roll back to a build without a lot of the new functionality. Using atomic commits, however, you’ll be able to avoid unnecessary, redundant work in the case that something goes wrong during development. A Non-standard Approach Is Not Necessarily a Bad Approach For loading high scores, I needed the UI layout to display the registered items. To do so, I had could either use data binding or write a simple routine that would generate XAML items on the fly in the code-behind. Data binding is a pretty common practice among XAML developers, so my initial thought was to use that, but I would have had to create a C++ binding harness in addition to the existing data retrieval code. The second approach was much cleaner because it didn’t require me to rewrite or add much code. The lesson here: pick the best approach for the job and don’t blindly follow programming trends. Focus on the User Experience At the end of the day, the user doesn’t care whether you wrote the application in native DirectX or XNA, whether you applied the MVVM pattern, or whether you have easily readable code. The user cares about having a great time while playing the game, regardless of its backbone. It’s your goal as a developer to deliver that user experience and ensure that the user feels comfortable with the product. This means that the development cycle goes beyond simply writing code. In FallFury, levels are dynamic, which means the source code doesn’t necessarily need to be modified in order to create a different playable experience. But that experience matters in any case, and level design is a huge part of FallFury’s final product. Users need to be immersed in the game world, so levels must be planned in such as way that the user returns to the game and doesn’t abandon it after a couple of lost rounds. Conclusion FallFury was my first major project that I wrote almost entirely in C++, targeting the newly released Windows 8 operating system. Although the development process was challenging, it was proven to be a great educational experience that taught me about the approaches and practices that are used internally at Microsoft. ]]> https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-12-Conclusions Project ConclusionsDeveloping FallFury was a fun and educational activity. Besides the fact that I got to work with an amazing team of people who were willing to assist me with the testing and development, I learned some important points about the development process as a whole and have outlined them in this article. Check out the video for this article at https://channel9.msdn.com/Series/FallFury/Part-12-Project-Conclusion. For a complete, offline version of this series, you may download a nicely formatted PDF of all the articles. Go Outside Your Comfort ZoneThis past summer, I decided to tackle a new challenge—game development. Never before had I built a game from the ground up. Moreover, as I could already find my way around C# code, I decided that I wanted to make C&#43;&#43; the language of choice, and so worked with DirectX instead of XNA. Additionally, the project needed to be constructed with Windows 8 as the target platform and I’d have to rely on the WinRT stack. The concepts were new to me, but I figured that learning about a new platform and a new language would be more interesting than sticking to my comfort zone. Through FallFury I extended my knowledge about pointers, trigonometry, how DirectX handles a lot of the graphics legwork, and how to write HLSL shaders. It was a challenging but very rewarding experience. CommunicateThe most important part of any project is communication. There are always people who know more than you in one field or another, so don't hesitate to reach out to other developers and ask questions. Your code is not perfect, so talk about best practices used in production and how you can improve on what you already have—communication should not be limited to your team, floor, or even building. One bonus of my experience at Microsoft was discovering that a lot of developers, when not in a meeting or in the middle of an important assignment, are more than happy to help a fellow employee with a piece of advice or some code review. P https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-12-Conclusions Wed, 23 Jan 2013 23:57:48 GMT https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-12-Conclusions Brian Peek, Clint Rutkas, Dan Fernandez, Den Delimarsky, Rick Barraza Brian Peek, Clint Rutkas, Dan Fernandez, Den Delimarsky, Rick Barraza 0 https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-12-Conclusions/RSS C# C++ Windows Store App Fall Fury: Part 11 - Hardware Testing & Debugging Hardware Testing & Debugging As previously mentioned, FallFury runs on multiple types of hardware as long as that hardware supports Windows 8. This article describes the project’s general testing and debugging process, including setting the debug configurations and remote debugging. Check out the video for this article at https://channel9.msdn.com/Series/FallFury/Part-11-Hardware-Testing.  For a complete, offline version of this series, you may download a nicely formatted PDF of all the articles. Remote Debug When working on an application that targets different machines, it’s probably out of the question to install Visual Studio on each instance and move the solution from one source to another in order to run it and diagnose potential problems. Here is where Remote Tools for Visual Studio 2012 come into play. Microsoft offers you three separate builds—tools for x86 systems, x64 systems, and ARM systems—also known as Surface RT. Once the tools are running on the machine you want to debug, you have two choices. You can either install the remote debugger as a service, allowing it to constantly run in the background, or you can use the debugger on a per-launch basis. From a developer perspective, the choice doesn’t affect how your application is executed on the remote machine. From a security perspective, however, you need to be sure that you properly configure it so that no unwanted apps are remotely deployed. Now you can start the Remote Debugger Configuration Wizard: clip_image002 clip_image004 This works on both the initial start-up and also any subsequent launch as a way to easily and quickly set the necessary remote debugger settings. Specifically, it is useful to configure the machine’s network settings, allowing cross-domain communications for debugging purposes. Once the wizard is completed, launch the Remote Debugger Monitor. Notice that it lists your machine name and the port on which it’s running. This is necessary for configuring the project to send the package to a remote machine instead of the local one: clip_image006 The configuration depends on the network settings on both the local machine and the subnet as a whole. For example, in some cases, and especially on domain-joined machines, remote debugging is better done with the authentication disabled. Windows Authentication is used by default. Since FallFury is a C++ project, the configuration for a remote session is different than, say, that of a C# Windows Store application. To configure the session, right click on the project in Solution Explorer and open the Debugging section. Make sure that Remote Machine is selected as the type of debugger to launch: clip_image008 Next, specify the machine name as well as whether the current session will require authentication: clip_image010 If you cannot specify the machine name, use the direct IPv4 address of that computer, minus the port (unless you’ve explicitly set it to a port other than 4016, which is the assumed default). Once the source machine connects to the remote one, you will see Visual Studio performing the deployment: clip_image012 Configurations As a matter of convenience, it is always good to have different debug configurations that will define how your projects are built, especially if the project targets multiple platforms (such as ARM and x86). Visual Studio provides a Configuration Manager that can be accessed from the debug target dropdown: clip_image013 FallFury includes two separate projects—the game core, and the C#-based XML reader. Both need to be explicitly associated with separate target platforms in order to be correctly debugged. For that, profiles were created for both local and remote sessions: clip_image014 As with standard Debug/Release configurations, the ones shown above determine whether the project will carry debug symbols and support debugging commands. It is important to mention that as you switch configurations, you must be careful how you configure the graphic shaders. For each shader in the container folder, explicitly set the HLSL shader type and model. Otherwise the application deployment will fail: clip_image016 Remote Profiling Last but not least, when working with different hardware configurations it might be useful to perform application profiling or performance review. Fortunately, Visual Studio also provides this capability through the vsperf tool, which is already integrated in the IDE if you are using Visual Studio 2012 Professional or above. To initiate a profiling session on a remote device, the Remote Debugger Monitor must be active. Make sure that the Remote Machine debug target is selected, and go to Analyze > Start Performance Analysis: clip_image017 On the remote machine, allow the vsperf process to run with administrative privileges. Once the profiling session completes and the data is analyzed, you can review the same performance indicators as you would when having a standard application run the profiler on the local machine: clip_image019 Conclusion Testing hardware outside the boundaries of a desktop machine is often a necessity, especially if the application relies on specific sensors, such as NFC, touch, or accelerometer. The remote debugging process is fairly streamlined and intuitive, with developing a proper network configuration allowing communication between machines requiring the most significant amount of effort. If you have problems getting the debugger to work, consult this article on MSDN. ]]> https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-11-Hardware-Testing--Debugging Hardware Testing &amp; DebuggingAs previously mentioned, FallFury runs on multiple types of hardware as long as that hardware supports Windows 8. This article describes the project’s general testing and debugging process, including setting the debug configurations and remote debugging. Check out the video for this article at https://channel9.msdn.com/Series/FallFury/Part-11-Hardware-Testing. For a complete, offline version of this series, you may download a nicely formatted PDF of all the articles. Remote DebugWhen working on an application that targets different machines, it’s probably out of the question to install Visual Studio on each instance and move the solution from one source to another in order to run it and diagnose potential problems. Here is where Remote Tools for Visual Studio 2012 come into play. Microsoft offers you three separate builds—tools for x86 systems, x64 systems, and ARM systems—also known as Surface RT. Once the tools are running on the machine you want to debug, you have two choices. You can either install the remote debugger as a service, allowing it to constantly run in the background, or you can use the debugger on a per-launch basis. From a developer perspective, the choice doesn’t affect how your application is executed on the remote machine. From a security perspective, however, you need to be sure that you properly configure it so that no unwanted apps are remotely deployed. Now you can start the Remote Debugger Configuration Wizard: This works on both the initial start-up and also any subsequent launch as a way to easily and quickly set the necessary remote debugger settings. Specifically, it is useful to configure the machine’s network settings, allowing cross-domain communications for debugging purposes. Once the wizard is completed, launch the Remote Debugger Monitor. Notice that it lists your machine name and the port on which it’s running. This is necessary for configuring the project to send the package to a remote machin https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-11-Hardware-Testing--Debugging Wed, 23 Jan 2013 23:57:44 GMT https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-11-Hardware-Testing--Debugging Brian Peek, Clint Rutkas, Dan Fernandez, Den Delimarsky, Rick Barraza Brian Peek, Clint Rutkas, Dan Fernandez, Den Delimarsky, Rick Barraza 3 https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-11-Hardware-Testing--Debugging/RSS C# C++ DirectX Windows Store App Fall Fury: Part 10 - Charms Charms With the release of the Windows 8 operating system, applications are now able to easily integrate with each other and have a unified way to control their workflow through unique system-wide contracts called Charms. Out of the multitude of available options, FallFury leverages two charms—Share contract and Settings. This article describes how the integration is implemented. Check out the video for this article at https://channel9.msdn.com/Series/FallFury/Part-10-Charms .  For a complete, offline version of this series, you may download a nicely formatted PDF of all the articles. clip_image002 The Share Contract When a user achieves a specific score in the game, he might decide to share it with his social circle. In Charms, that’s the purpose of the Share contract, which integrates directly with the OS. Windows Store applications have the capability to expose their sharing capabilities and register as a share target. For example, if there is a Twitter client out, it can register itself as an app through which content can be shared. FallFury, on the other hand, acts as a consumer that aggregates existing share targets and lets the user pick the one through which he wants to let the message out: clip_image004 Let’s take a look at how this process is built in the code-behind. The core is located in DirectXPage.xaml.cpp—the class responsible for XAML content manipulation in FallFury. First and foremost, you need to get the current instance of the DataTransferManager class: auto dataTransferManager = Windows::ApplicationModel::DataTransfer::DataTransferManager::GetForCurrentView(); Consider this a proxy that allows you to pass content between your app and other Windows Store apps that are executed in the context of the same sandbox. As the instance is obtained, hook it to the DataRequested event handler that will handle the scenario where the user invoked the sharing capability: dataTransferManager->DataRequested += ref new TypedEventHandler<Windows::ApplicationModel::DataTransfer::DataTransferManager^, Windows::ApplicationModel::DataTransfer::DataRequestedEventArgs^>(this, &DirectXPage::OnShareDataRequested);   In the OnShareDataRequested, specify the information that goes into the sharing popup: void DirectXPage::OnShareDataRequested(Windows::ApplicationModel::DataTransfer::DataTransferManager^ manager,Windows::ApplicationModel::DataTransfer::DataRequestedEventArgs^ params) { auto request = params->Request; request->Data->Properties->Title = "Share Score"; request->Data->Properties->Description = "Tell your friends how much you scored in [DEN'S PROJECT]!"; request->Data->SetText("I just scored " + StaticDataHelper::Score.ToString() + " in [DEN'S PROJECT]! Beat me! http://dennisdel.com"); }   From that point, the control is in the user’s hand. The application cannot force the share, so unless you implement a direct API hook to a social service, the Share charm will only expose the endpoints available for sharing and will let you set the shareable content. You also don’t have to worry about the way the content will be shared—that will be handled by the target application: clip_image006 You can show the popup triggered by the Share charm from your application without having the user open the Charms Bar. To do this, call the ShowShareUI method: void DirectXPage::ShareTopScore_Selected(MenuItem^ sender, Platform::String^ params) { Windows::ApplicationModel::DataTransfer::DataTransferManager::ShowShareUI(); }   This is exactly what the Share button does in the screenshot above. You should make this behavior predictable. The Settings Charm As you just saw, integrating basic sharing capabilities in FallFury is not too complicated. Working with settings is also a fairly easy task, though it involves some XAML work. While with sharing capabilities the work focused mostly on OS-based endpoints and application-specific popups, settings allow for full control over how they’re displayed. For all Windows Store applications, settings should be handled via the Settings charm and not through dedicated application screens. Consider which settings that directly affect the user experience might be changed in FallFury: clip_image008 • Music and SFX – the user can enable or disable music and sound effects, as well as control their volume. • Accelerometer – depending on personal preferences, the user might decide to disable the accelerometer (it is enabled by default). The accelerometer can also be inverted—if the device is tilted to the right, the character will move to the left and vice-versa. Last but not least, even with dynamic screen rotation enabled on the device, the user can disable that rotation on the application level and lock the screen to one orientation, such as portrait or landscape. • Character Movement – the character can be easily controlled via touch (swipe) or mouse. This behavior is enabled by default, but if the user decides to only use the mouse to direct shells, he can easily disable this feature here. As seen in the image above, the operating system provides the basic shell used to list the possible settings. Once one option is selected, however, further UI displays are delegated to the developer. As with the share UI, the settings UI can be shown to the user from the application and not from the Charms Bar. Here is how to do this: void DirectXPage::Settings_Selected(MenuItem^ sender, Platform::String^ params) { SettingsPane::GetForCurrentView()->Show(); }   SettingsPane is the core class that handles the settings display. It does not control how settings are stored or activated. When the main page loads, you need to make sure that you hook the current SettingsPane to a CommandRequested event handler. It will be triggered when the Settings capability is invoked: SettingsPane::GetForCurrentView()->CommandsRequested += ref new TypedEventHandler<SettingsPane^, SettingsPaneCommandsRequestedEventArgs^>(this, &DirectXPage::OnSettingsRequested); OnSettingsRequested is the function where the core setting selections are defined and hooked to their own event handlers: void DirectXPage::OnSettingsRequested(Windows::UI::ApplicationSettings::SettingsPane^ settingsPane, Windows::UI::ApplicationSettings::SettingsPaneCommandsRequestedEventArgs^ eventArgs) { if (m_renderer->CurrentGameState == GameState::GS_PLAYING) StaticDataHelper::IsPaused = true; UICommandInvokedHandler^ handler = ref new UICommandInvokedHandler(this, &DirectXPage::OnSettingsSelected); SettingsCommand^ generalCommand = ref new SettingsCommand("musicSfx", "Music & SFX", handler); eventArgs->Request->ApplicationCommands->Append(generalCommand); SettingsCommand^ accelerometerCommand = ref new SettingsCommand("accelerometer", "Accelerometer", handler); eventArgs->Request->ApplicationCommands->Append(accelerometerCommand); SettingsCommand^ charMovementCommand = ref new SettingsCommand("charMovement", "Character Movement", handler); eventArgs->Request->ApplicationCommands->Append(charMovementCommand); } Each SettingsCommand is an item in the list displayed in the settings pane. When one is selected, OnSettingsSelected is called: void DirectXPage::OnSettingsSelected(Windows::UI::Popups::IUICommand^ command) { if (command->Id->ToString() == "musicSfx") { stkMusicSfx->Width = 346.0f; grdSubMusicSfx->Height = m_renderer->m_renderTargetSize.Height; stkMusicSfx->IsOpen = true; } else if (command->Id->ToString() == "accelerometer") { stkAccelerometerSettings->Width = 346.0f; grdAccelerometerSettings->Height = m_renderer->m_renderTargetSize.Height; stkAccelerometerSettings->IsOpen = true; } else if (command->Id->ToString() == "charMovement") { stkCharacterMovement->Width = 346.0f; grdCharacterMovement->Height = m_renderer->m_renderTargetSize.Height; stkCharacterMovement->IsOpen = true; } WindowActivationToken = Window::Current->Activated += ref new WindowActivatedEventHandler(this, &DirectXPage::OnWindowActivated); } Looking back at OnSettingsRequested, each command has a string identifier. When a command is invoked, that string identifier is returned through the IUICommand instance in the Id property. Based on that, I decided which popups to open. Since each has a similar structure, I am going to cover the implementation of just one—Music & SFX. Here is what the end result looks like: clip_image010 The panel on the left is a Popup, with two ToggleButton controls used to enable or disable generic music and sound effects. There are also two Slider controls that are used to adjust the volume. The XAML for the above layout looks like this: <Popup HorizontalAlignment="Right" IsLightDismissEnabled="True" x:Name="stkMusicSfx" > <Grid Background="Black" x:Name="grdSubMusicSfx" Width="346"> <Grid.Transitions> <TransitionCollection> <RepositionThemeTransition /> </TransitionCollection> </Grid.Transitions> <Grid.RowDefinitions> <RowDefinition Height="120"></RowDefinition> <RowDefinition Height="*"></RowDefinition> </Grid.RowDefinitions> <StackPanel Grid.Row="0" Orientation="Horizontal" Margin="24,12,0,0" > <Button Margin="0" VerticalAlignment="Center" x:Name="dismissAudioSettings" Click="dismissAudioSettings_Click" Style="{StaticResource BackButtonStyle}"></Button> <TextBlock Margin="12,0,0,12" Height="Auto" VerticalAlignment="Center" Text="Music &amp; SFX" Style="{StaticResource SubheaderTextStyle}"></TextBlock> </StackPanel> <StackPanel Grid.Row="1" Margin="24,24,0,0"> <StackPanel> <TextBlock Text="Music" Style="{StaticResource BodyTextStyle}"></TextBlock> <TextBlock Width="346" Text="This includes the theme track and level background music." Style="{StaticResource CaptionTextStyle}" TextWrapping="Wrap" Margin="0,12,12,12" ></TextBlock> <ToggleSwitch x:Name="tglMusic" Toggled="tglMusic_Toggled" IsOn="{Binding ElementName=XAMLPage,Path=MusicEnabled}" Margin="-6,0,0,0"></ToggleSwitch> </StackPanel> <StackPanel Margin="0,24,0,0"> <TextBlock Text="Music Volume" Style="{StaticResource BodyTextStyle}"></TextBlock> <Slider x:Name="sldMusicVolume" ValueChanged="sldMusicVolume_ValueChanged" Value="{Binding ElementName=XAMLPage,Path=MusicVolume, Mode=TwoWay}" Minimum="0" Maximum="100" Margin="0,0,12,0"></Slider> </StackPanel> <StackPanel Margin="0,24,0,0"> <TextBlock Text="Sound Effects" Style="{StaticResource BodyTextStyle}"></TextBlock> <TextBlock Width="346" Text="Includes sounds played during the game (e.g. explosions)." Style="{StaticResource CaptionTextStyle}" TextWrapping="Wrap" Margin="0,12,12,12" ></TextBlock> <ToggleSwitch x:Name="tglSFX" Toggled="tglSFX_Toggled" IsOn="{Binding ElementName=XAMLPage,Path=SFXEnabled}" Margin="-6,0,0,0"></ToggleSwitch> </StackPanel> <StackPanel Margin="0,24,0,0"> <TextBlock Text="SFX Volume" Style="{StaticResource BodyTextStyle}"></TextBlock> <Slider x:Name="sldSFXVolume" ValueChanged="sldSFXVolume_ValueChanged" Value="{Binding ElementName=XAMLPage,Path=SFXVolume, Mode=TwoWay}" Minimum="0" Maximum="100" Margin="0,0,12,0"></Slider> </StackPanel> </StackPanel> </Grid> </Popup> For every Popup instance used for settings, make sure that IsLightDismissEnabled is set to true. This allows the user to dismiss the panel with a touch outside its boundaries, just like the stock system panels. Other than that, you are working with the standard XAML control set and can include virtually anything in your settings. Notice, that the switches and sliders are bound to internal properties, such as SFXEnabled and MusicEnabled, that perform the binding via dependency property references: DependencyProperty^ DirectXPage::_musicEnabled = DependencyProperty::Register("MusicEnabled", bool::typeid, DirectXPage::typeid, nullptr); DependencyProperty^ DirectXPage::_sfxEnabled = DependencyProperty::Register("SFXEnabled", bool::typeid, DirectXPage::typeid, nullptr);   The properties themselves are declared in the DirectXPage header file: static property DependencyProperty^ SFXVolumeProperty { DependencyProperty^ get() { return _sfxVolume; } } property int SFXVolume { int get() { return (int)GetValue(SFXVolumeProperty); } void set(int value) { SetValue(SFXVolumeProperty, value); } } static property DependencyProperty^ MusicVolumeProperty { DependencyProperty^ get() { return _musicVolume; } } property int MusicVolume { int get() { return (int)GetValue(MusicVolumeProperty); } void set(int value) { SetValue(MusicVolumeProperty, value); } } Let’s take a quick look at how settings are stored. I have a class called SettingsHelper that allows me to save, read, and check if specific settings exist. Here is the implementation: #include "pch.h" #include "SettingsHelper.h" using namespace Windows::Storage; using namespace Coding4Fun::FallFury::Helpers; SettingsHelper::SettingsHelper(void) { } void SettingsHelper::Save(Platform::String^ key, Platform::Object^ value) { ApplicationDataContainer^ localSettings = ApplicationData::Current->LocalSettings; auto values = localSettings->Values; values->Insert(key, value); } Platform::Object^ SettingsHelper::Read(Platform::String^ key) { ApplicationDataContainer^ localSettings = ApplicationData::Current->LocalSettings; auto values = localSettings->Values; return values->Lookup(key); } bool SettingsHelper::Exists(Platform::String^ key) { ApplicationDataContainer^ localSettings = ApplicationData::Current->LocalSettings; auto values = localSettings->Values; return values->HasKey(key); }   It is clear that storage and retrieval heavily relies on the ApplicationDataContainer class, the container class for local settings that eliminates the need for the developer to create his own setting files, instead delegating this task to the OS and utilizing a centralized storage for all Windows Store applications. A typical scenario that utilizes the class above is executed when the toggle that manages the sound effects is switched: void DirectXPage::tglSFX_Toggled(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { SettingsHelper::Save("sfxEnabled", tglSFX->IsOn); SFXEnabled = tglSFX->IsOn; AudioManager::IsSFXStarted = SFXEnabled; if (SFXEnabled) { AudioManager::AudioEngineInstance.StartSFX(); } else { AudioManager::AudioEngineInstance.SuspendSFX(); } }   The Boolean value above will be automatically serialized and stored. The files will be located at C:\Users\YOUR_USER_NAME\AppData\Local\Packages\PACKAGE_ID\Settings\settings.dat:   clip_image012 Conclusion Implementing sharing through the OS channel in Windows 8 is extremely easy seeing as the developer does not necessarily have to worry about connecting the app to third-party API endpoints. Instead, the user controls the sharing, allowing flexibility of choice without requiring a major addition to the existing code base. It’s hard to predict which services might appear, and modifying the app to support each one of them would be next to impossible otherwise. You can read more about settings in Windows Store applications here. ]]> https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-10-Charms CharmsWith the release of the Windows 8 operating system, applications are now able to easily integrate with each other and have a unified way to control their workflow through unique system-wide contracts called Charms. Out of the multitude of available options, FallFury leverages two charms—Share contract and Settings. This article describes how the integration is implemented. Check out the video for this article at https://channel9.msdn.com/Series/FallFury/Part-10-Charms . For a complete, offline version of this series, you may download a nicely formatted PDF of all the articles. The Share ContractWhen a user achieves a specific score in the game, he might decide to share it with his social circle. In Charms, that’s the purpose of the Share contract, which integrates directly with the OS. Windows Store applications have the capability to expose their sharing capabilities and register as a share target. For example, if there is a Twitter client out, it can register itself as an app through which content can be shared. FallFury, on the other hand, acts as a consumer that aggregates existing share targets and lets the user pick the one through which he wants to let the message out: Let’s take a look at how this process is built in the code-behind. The core is located in DirectXPage.xaml.cpp—the class responsible for XAML content manipulation in FallFury. First and foremost, you need to get the current instance of the DataTransferManager class: auto dataTransferManager = Windows::ApplicationModel::DataTransfer::DataTransferManager::GetForCurrentView(); Consider this a proxy that allows you to pass content between your app and other Windows Store apps that are executed in the context of the same sandbox. As the instance is obtained, hook it to the DataRequested event handler that will handle the scenario where the user invoked the sharing capability: dataTransferManager-&gt;DataRequested &#43;= ref new TypedEventHandler&lt;Windows::ApplicationModel::Dat https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-10-Charms Wed, 23 Jan 2013 23:57:40 GMT https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-10-Charms Brian Peek, Clint Rutkas, Dan Fernandez, Den Delimarsky, Rick Barraza Brian Peek, Clint Rutkas, Dan Fernandez, Den Delimarsky, Rick Barraza 0 https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-10-Charms/RSS C# C++ DirectX Windows Store App Fall Fury: Part 9 - Particle System Particle System During gameplay there are scenarios during which users need to be visually notified that something has happened, such as a collision with an obstacle or an enemy shell. One way to do this is by having explosion or item breaking simulation, which brings us to the next large component in FallFury—the sprite-based particle system. It doesn’t offer as much power as a full-fledged particle system would, but it allows for effects that fit well within the overall theme and layout of the game. Check out the video for this article at https://channel9.msdn.com/Series/FallFury/Part-9-Particle-System .  For a complete, offline version of this series, you may download a nicely formatted PDF of all the articles. The Core ParticleSystem is the dedicated folder in the project that contains everything needed to render multiple textures at once and displace them to create the desired effect: clip_image001 A single particle carries information regarding its size, position, velocity, color shading, rotation, circular velocity, and scale. As with any other rendered entity, it has a bounding box that can be used to detect its intersection with other elements on the screen. In FallFury, this functionality is not used. Its structure is as follows: #pragma once #include "pch.h" struct Particle { Particle(float2 size); Particle(float2 size, float4 shading); float2 Size; float2 Position; float2 Velocity; float4 Shading; float Rotation; float RotationVelocity; float Scale; bool IsWithinScreenBoundaries(float x, float y, Windows::Foundation::Rect screenBounds); Windows::Foundation::Rect GetBoundingBox(); }; The Particle class also happens to have two constructors—one that sets the particle to have the default shading, effectively removing the effect, and one where shading is dynamic. Note that a particle on its own doesn’t do much—it neither carries the associated texture nor has an internal loop that can be used in any given application part to display it. The next core class is ParticleSet. It is used as a container for all the particles associated with a specific effect. For example, if I want to create flying stuffing when the bear hits an obstacle, I create a new ParticleSet instance and define the necessary particle properties: • Lifespan – a particle set does not constantly animate. It displays the particles for a limited amount of time, and displaces them by the given velocity values, and then self-destructs. • Texture – all particles in a ParticleSet have the same texture. Going back to the stuffing example, there is a single PNG file used to render multiple variable-sized particles on collision. • IsAlive – this is the flag that shows whether the particle set should be rendered in the first place. If it is set to false then, regardless of the conditions, this ParticleSet instance is ignored. • ShouldScale – this flag determines whether particles will automatically increase their scale as they are being displaced, creating the effect of a particle approaching the screen. This effect is applied to each particle in the set. The container class is used to update the particles through the Update function: void ParticleSet::Update(float timeDelta) { float quat = _lifespan / 0.016f; float decrement = 1.0f / quat; if (_totalTime <= _lifespan && _isAlive) { _totalTime += timeDelta; for (auto particle = _particles.begin(); particle != _particles.end(); particle++) { if (_shouldScale) particle->Scale += 0.2f; particle->Shading.a -= decrement; particle->Position = float2(particle->Position.x + particle->Velocity.x, particle->Position.y + particle->Velocity.y); if (!_shouldScale) particle->Rotation += particle->RotationVelocity; } } else { _totalTime = 0.0f; _isAlive = false; } } As it relies on the _isAlive flag, the Update loop is only used when the particle displacement is activated via the Activate function: void ParticleSet::Activate(float2 position, float2 velocity, bool randomize, bool scale) { for (auto particle = _particles.begin(); particle != _particles.end(); particle++) { particle->Position = position; if (randomize) particle->Velocity = float2(RandFloat(-5.0f,5.0f), RandFloat(-5.0f, 5.0f)); else particle->Velocity = float2(velocity.x + RandFloat(-0.6f, 0.6f), velocity.y + RandFloat(-0.6f, 0.6f));; } _shouldScale = scale; _isAlive = true; } When a set is activated, several user-defined parameters come into play. The position is set no matter what and is used to create the source point from which the particles start appearing. The velocity, on the other hand, can be randomized between the values of -5 and 5 pixels per update loop, on both the X-axis and the Y-axis. If randomized, large amount of particles will create an explosion that starts from the center point and expands towards all quadrants. When the velocity is not randomized, it creates a triangular expansion grid on which particles deviate from the center point in one of the given directions: clip_image003 When it’s time to render the particles, the sprite batch associated with the current game screen is used to pass a texture for each particle registered in the set: void ParticleSet::Render(SpriteBatch ^spriteBatch) { for (auto particle = _particles.begin(); particle != _particles.end(); particle++) { if (GamePlayScreen::Manager->IsWithinScreenBoundaries(particle->Position)) spriteBatch->Draw(_texture.Get(), particle->Position, PositionUnits::DIPs, particle->Size * particle->Scale, SizeUnits::Pixels, particle->Shading, particle->Rotation); } } Although there is no flag check inside the Render method that would make sure that the set is alive, this can be done outside of it by calling IsAlive, which will return the flag value: bool ParticleSet::IsAlive() { return _isAlive; }   Let’s now take a look at the class that managed the particle flow—ParticleCore. The Particle Manager ParticleCore is the class that manages internal particle sets, and is also the proxy for set activation, update, and rendering. Here is its structure: #pragma once #include "pch.h" #include "ParticleSet.h" #include <list> #include <map> class ParticleCore { public: ParticleCore(); ParticleCore(Coding4Fun::FallFury::Screens::GameScreenBase^); virtual ~ParticleCore(); void CreatePreCachedParticleSets(); void ActivateSet(Platform::String^, float2); void ActivateSet(Platform::String^, float2, float2); void ActivateSet(Platform::String^, float2, bool); void ActivateSet(Platform::String^, float2, float2, bool); void ActivateSet(Platform::String^, float2, float2, bool, bool scale); void Update(float); void Render(); private: std::list<ParticleSet> _renderParticleSets; std::map<Platform::String^, ParticleSet*> _particleSetCache; std::map<Platform::String^, Microsoft::WRL::ComPtr<ID3D11Texture2D>> _textureCache; Coding4Fun::FallFury::Screens::GameScreenBase^ _screenBase; }; As previously mentioned, set activation can be done with some omitted parameters inferred by the system, such as randomization of velocity or particle scaling, which is the reason why you see multiple overloads for ActivateSet. ParticleCore is also the container for pre-defined sets that have specific textures and properties that are dumped in the particle set cache (internal _particleSetCache). The cache is reusable and even though sets can be activated and destroyed, the cache remains intact for the duration of the game unless explicitly reset or modified. The texture cache is an addition to the particle set cache and is used as a helper container to temporarily store the textures used for individual particles. Taking a look under the hood at the CreatePreCachedParticleSets function, you can see multiple sets that can be used in the game, each with different properties. Here is a snippet that shows how the bear stuffing explosion set is created: auto smallExplosionSet = new ParticleSet(_textureCache["Stuffing"], LIFESPAN); for (int i = 0; i < 20; i++) { float size = RandFloat(50.0f, 100.0f); Particle particle(float2(size, size)); smallExplosionSet->AddParticle(particle); }   Once all the particles are in place for that specific set, it is added to the global particle set cache: _particleSetCache["SmallExplosion"] = smallExplosionSet; The particle set cache is not explicitly used to render anything on the screen. Rather, that task is delegated to the rendering cache. When a set is activated, the cache is inspected for the given key, its Activate function is called, marking it as alive, and the set itself is pushed on the rendering stack: void ParticleCore::ActivateSet(Platform::String^ name, float2 position, float2 velocity, bool randomize, bool scale) { ParticleSet set = ParticleSet(*_particleSetCache[name]); set.Activate(position, velocity, randomize, scale); _renderParticleSets.push_back(set); }   The Render loop takes care of invoking the proper SpriteBatch drawing functions for each set that is in that stack: void ParticleCore::Render() { for (auto set = _renderParticleSets.begin(); set != _renderParticleSets.end(); ++set) { if ((*set).IsAlive()) { (*set).Render(_screenBase->CurrentSpriteBatch); } } }   Notice that, as previously mentioned, the set does not perform the life check on itself when rendering. Instead, the manager class performs this action. The same applies to the Update loop: void ParticleCore::Update(float timeDelta) { for (auto set = _renderParticleSets.begin(); set != _renderParticleSets.end();) { if ((*set).IsAlive()) { (*set).Update(timeDelta); ++set; } else { set = _renderParticleSets.erase(set); } } }   The textures for each set are individually loaded in the CreatePreCachedParticleSets. Each instance is internally pushed into the cache and also added to the sprite batch associated with the current game screen, where ParticleCore is used: Loader->LoadTexture("DDS\\stuffing.dds", &_textureCache["Stuffing"], nullptr); _screenBase->CurrentSpriteBatch->AddTexture(_textureCache["Stuffing"].Get());   Once everything is loaded, the ParticleCore is ready to go and you can use as many particles as necessary in any part of the application. In GamePlayScreen, particle sets are activated in many cases. For example, if the bear dies: void GamePlayScreen::CheckBearHealth() { if (GameBear->CurrentHealth <= 0) { m_particleSystem.ActivateSet("Buttons",GameBear->Position, true); GameBear->Kill(); StopBackground(); } }   Conclusion Implementing a sprite-based particle system is not complicated, but it requires depending on a number of assumptions. For example, when a particle set is created, you might consider the fact that some hardware can handle drawing only a given number of sprites at the same time. If a particle set is rendered on a desktop machine, there is no guarantee that the same set will successfully render on an ARM device. Therefore, plan accordingly. For each particle set, create a lifespan that fits the scenario without wasting resources on rendering unnecessary particles. As an additional failsafe, you might want to disable specific particle set types when a Direct3D feature level below 10.0 is detected. ]]> https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-9-Particle-System Particle SystemDuring gameplay there are scenarios during which users need to be visually notified that something has happened, such as a collision with an obstacle or an enemy shell. One way to do this is by having explosion or item breaking simulation, which brings us to the next large component in FallFury—the sprite-based particle system. It doesn’t offer as much power as a full-fledged particle system would, but it allows for effects that fit well within the overall theme and layout of the game. Check out the video for this article at https://channel9.msdn.com/Series/FallFury/Part-9-Particle-System . For a complete, offline version of this series, you may download a nicely formatted PDF of all the articles. The CoreParticleSystem is the dedicated folder in the project that contains everything needed to render multiple textures at once and displace them to create the desired effect: A single particle carries information regarding its size, position, velocity, color shading, rotation, circular velocity, and scale. As with any other rendered entity, it has a bounding box that can be used to detect its intersection with other elements on the screen. In FallFury, this functionality is not used. Its structure is as follows: #pragma once #include &quot;pch.h&quot; struct Particle { Particle(float2 size); Particle(float2 size, float4 shading); float2 Size; float2 Position; float2 Velocity; float4 Shading; float Rotation; float RotationVelocity; float Scale; bool IsWithinScreenBoundaries(float x, float y, Windows::Foundation::Rect screenBounds); Windows::Foundation::Rect GetBoundingBox(); }; The Particle class also happens to have two constructors—one that sets the particle to have the default shading, effectively removing the effect, and one where shading is dynamic. Note that a particle on its own doesn’t do much—it neither carries the associated texture nor has an internal loop that can be used in any g https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-9-Particle-System Wed, 23 Jan 2013 23:57:36 GMT https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-9-Particle-System Brian Peek, Clint Rutkas, Dan Fernandez, Den Delimarsky, Rick Barraza Brian Peek, Clint Rutkas, Dan Fernandez, Den Delimarsky, Rick Barraza 0 https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-9-Particle-System/RSS C# C++ DirectX Windows Store App Fall Fury: Part 8 - Element Interaction Element Interaction During the gameplay multiple entities interact with each other to make the gaming experience what it is. The bear collides with obstacles and collects buttons, monsters shoot shells that can fly off-screen or hit the bear—all this is possible with the help of the basic collision detection techniques that are implemented in FallFury. Check out the video for this article at https://channel9.msdn.com/Series/FallFury/Part-8-Element-Interaction . For a complete, offline version of this series, you may download a nicely formatted PDF of all the articles. Buttons Buttons are bonus-boosters that can be placed by the level designer anywhere on the screen in game mode. These are relatively small entities, which are displaced vertically with each cycle of the Update loop and move in the opposite direction, but with the same velocity, as the main character. image Looking at the Update function in the GamePlayScreen class, you will notice this call: UpdateButtons(); UpdateButtons can be considered the button manager function responsible for removing the collected buttons from the rendering stack, counting them, and checking for a button collision when the bear is in close proximity. The implementation looks like this: void GamePlayScreen::UpdateButtons() { Windows::Foundation::Rect livingEntityBoundingBox = GameBear->GetBoundingBox(); for (auto button = m_buttons.begin(); button != m_buttons.end();) { (*button)->Position.x = (*button)->PixelDiff + LoBoundX; (*button)->Position.y -= GameBear->Velocity.y; if (Geometry::IsInProximity(GameBear->Position,(*button)->Position, 100)) { Windows::Foundation::Rect obstacleRect = (*button)->GetBoundingBox(); if (livingEntityBoundingBox.IntersectsWith(obstacleRect)) { AudioManager::AudioEngineInstance.StopSoundEffect(Coin); AudioManager::AudioEngineInstance.PlaySoundEffect(Coin); m_particleSystem.ActivateSet("Sparkle", (*button)->Position,float2(RandFloat(-6.0f,6.0f),RandFloat(-10.0f, -5.0f))); StaticDataHelper::ButtonsCollected++; button = m_buttons.erase(button); } else ++button; } else { ++button; } } } For performance reasons, FallFury supports composite bounding box creation as well as simple box creation. As mentioned earlier in the series, the main character is not composed of a single texture, but rather multiple sprites that are cross-positioned to create a single visual entity. To give you a better idea of what composite vs. simple boxing looks like, take a look at the images below: imageimage The image on the left shows how each part of the bear has its own bounding box, and each will be used for collision checking. In the image on the right, the bear has a single bounding box, creating minor potential gaps, but gaining performance. Going back to UpdateButtons, once the bounding box is obtained, I iterate through the button collection and make sure that each item is located in the proper space: (*button)->Position.x = (*button)->PixelDiff + LoBoundX; (*button)->Position.y -= GameBear->Velocity.y;   The constant position checks are necessary because FallFury supports dynamic orientation changes. When the user switches from portrait to landscape mode and vice-versa, rendered elements on the screen are not automatically repositioned. Setting the X position is easy as long as there is a fixed button margin (from the left side of the screen: LoBoundX) and adding it to the current LoBoundX value results in a proper X location. There is no need to do the same check on the Y-axis because the level length remains the same regardless of the current screen orientation. The adjustment made relative the Y position is bound to the bear velocity. If the bear moves slower, buttons will also scroll slower. Given that all buttons are properly positioned, a proximity check is performed on each button passed through the loop. If the bear position is at least 100 pixels away from the current button, the corresponding bounding box is obtained and an intersect check is performed. In simple boxing mode, this is done via Windows::Foundation::Rect::IntersectsWith: image If a collision occurs, the appropriate sound effect is played and a particle set is activated to create a visual notification of the action. After the button counter is incremented, the button is removed from the local collection, effectively being removed from the rendering stack. Power-ups As the bear flies towards the end of the level, it might encounter bonuses to improve its ability to fight incoming enemies or protect from damage caused by enemy ammo or obstacles. The process behind displaying power-ups on the screen and determining whether there was a collision with the main character is similar to UpdateButtons. The core function for this task is UpdatePowerups: void GamePlayScreen::UpdatePowerups(float timeDelta) { if (m_powerups.size() > 0) { for (auto powerup = m_powerups.begin(); powerup != m_powerups.end(); powerup++) { (*powerup)->Update(timeDelta); (*powerup)->Position.x = (*powerup)->PixelDiff + LoBoundX; (*powerup)->Position.y -= GameBear->Velocity.y; } } CheckForCollisionWithPowerups(); }   One difference you probably noticed in the snippet above is the fact that the collision check is now done through a separate function—CheckForCollisionWithPowerups: void GamePlayScreen::CheckForCollisionWithPowerups() { Powerup^ currentPowerup; Windows::Foundation::Rect livingEntityBoundingBox = GameBear->GetBoundingBox(); for (auto powerup = m_powerups.begin(); powerup != m_powerups.end();) { currentPowerup = (*powerup); if (Geometry::IsInProximity(GameBear->Position,currentPowerup->Position, 100)) { Windows::Foundation::Rect obstacleRect = currentPowerup->GetBoundingBox(); if (livingEntityBoundingBox.IntersectsWith(obstacleRect)) { AudioManager::AudioEngineInstance.PlaySoundEffect(GenericPowerup); GameBear->PickupPowerup(currentPowerup, &m_particleSystem); powerup = m_powerups.erase(powerup); } else ++powerup; } else { ++powerup; } } } If an intersection is detected between the boxed bear and the power-up texture, the current power-up is passed to the Bear instance and the appropriate type of action is selected: void Bear::PickupPowerup(Powerup^ powerup, ParticleCore* ParticleSystem) { switch (powerup->Type) { case PowerupType::PARACHUTE: { m_previousVelocity = Velocity.y; SetParachute(powerup->Lifespan); Velocity.y -= powerup->Effect; ParticleSystem->ActivateSet("ScalableParachute", Position, 0.0f, false, true); break; } case PowerupType::HEALTH: { CurrentHealth = MaxHealth; ParticleSystem->ActivateSet("ScalableHeart", Position, 0.0f, false, true); break; } case PowerupType::BUBBLE: { if (IsHelmetEnabled) { IsHelmetEnabled = false; DamageDivider = 1.0f; } else { DamageDivider = powerup->Effect; } IsBubbleEnabled = true; m_maxBubbleCounter = powerup->Lifespan; ParticleSystem->ActivateSet("ScalableBubble", Position, 0.0f, false, true); break; } // [...] case PowerupType::BOOMERANG: { m_weaponType = powerup->Type; m_weaponTexture = m_boomerangTexture; CurrentDamage = powerup->Effect; m_weaponSize = float2(225.0f, 205.0f) * 0.5f; ParticleSystem->ActivateSet("ScalableBoomerang", Position, 0.0f, false, true); break; } } } Depending on the power-up, textures are added to the bear model and later passed to the rendering stack (if the power-up type is PARACHUTE), some textures and capabilities are replaced (BOOMERANG), or the bear capabilities are temporarily modified (BUBBLE): image If one of the temporary power-ups is enabled n the Update loop, dedicated timers ensure that ability enhancement does not last longer than necessary. As an example, here is the snippet that controls the bubble: if (IsBubbleEnabled) { m_currentBubbleCounter += timeDelta; if (m_currentBubbleCounter > m_maxBubbleCounter) { IsBubbleEnabled = false; DamageDivider = 1.0f; m_currentBubbleCounter = 0.0f; } }   Ammo Collisions There are also objects that direct ammo at either the enemy or the bear. After release, each shell follows a linear path towards the target, and while the user directs the shells that originate from the bear, those released by enemy entities automatically target the bear. In this case, the ammo needs to collide with an object to either damage or kill it. When a shell is released, it is added to the general ammo collection that is later updated internally: void GamePlayScreen::UpdateAmmo(float timeDelta) { for (auto shell = m_ammoCollection.begin(); shell != m_ammoCollection.end(); shell++) { (*shell)->Update(timeDelta, &m_particleSystem); } }   At this point, the rendering system does not differentiate between friendly and enemy ammo—all it knows is that each item in the collection must have a new position when a new frame is rendered. The CheckForCollisionsWithAmmo function checks for ammo collisions: void GamePlayScreen::CheckForCollisionWithAmmo(LivingEntity^ entity) { if (entity != nullptr) { Windows::Foundation::Rect livingEntityBoundingBox = entity->GetBoundingBox(); if (entity->IsFriendly) { for (auto ammo = m_ammoCollection.begin(); ammo != m_ammoCollection.end();) { if (!(*ammo)->IsFriendly) { Windows::Foundation::Rect ammoBoundingBox = (*ammo)->GetBoundingBox(); if (livingEntityBoundingBox.IntersectsWith(ammoBoundingBox)) { m_particleSystem.ActivateSet("SmallExplosion",entity->Position, true); entity->InflictDamage((*ammo)->HealthDamage); GameBear->RedShade(); AudioManager::AudioEngineInstance.PlaySoundEffect(OuchA); AudioManager::AudioEngineInstance.PlaySoundEffect(HardSoftCollision); CheckBearHealth(); ammo = m_ammoCollection.erase(ammo); } else { ++ammo; } } else { ++ammo; } } } else { for (auto ammo = m_ammoCollection.begin(); ammo != m_ammoCollection.end();) { if ((*ammo)->IsFriendly) { Windows::Foundation::Rect ammoBoundingBox = (*ammo)->GetBoundingBox(); if (livingEntityBoundingBox.IntersectsWith(ammoBoundingBox)) { Monster^ monster = ((Monster^)entity); if (!monster->IsDead && monster->IsActive) { m_particleSystem.ActivateSet("SmallExplosion", entity->Position, true); entity->InflictDamage((*ammo)->HealthDamage); monster->RedShade(); monster->CheckIfAlive(); AudioManager::AudioEngineInstance.PlaySoundEffect(SharpSoftCollision); } ammo = m_ammoCollection.erase(ammo); } else { ++ammo; } } else { ++ammo; } } } } } When the function is called, it is usually run against an entity that is present on the screen, such as the main character. Regardless of whether the enemy or the friendly character fired the shot, the shot cannot inflict damage to its source, and that’s why the function implements the ammo-to-entity crosscheck. If the ammo collides with any shells intersecting the entity bounding box, a collision is counted and health verification is performed to ensure that the character is still alive and that the game should continue. The bear’s health is checked via CheckBarHealth: void GamePlayScreen::CheckBearHealth() { if (GameBear->CurrentHealth <= 0) { m_particleSystem.ActivateSet("Buttons",GameBear->Position, true); GameBear->Kill(); StopBackground(); } } That said, not all ammo will collide with entities on the screen. Some of it will go out-of-bounds, and without an explicit cleanup process in place out-of-bounds ammo is constantly re-rendered even though the end user has no way of seeing it. To avoid this, there is a helper function—CheckForOutOfBoundsAmmo: void GamePlayScreen::CheckForOutOfBoundsAmmo() { for (auto l_Iter = m_ammoCollection.begin(); l_Iter != m_ammoCollection.end(); /* nothing here */ ) { if (!GamePlayScreen::Manager->IsWithinScreenBoundaries((*l_Iter)->Position)) { l_Iter = m_ammoCollection.erase(l_Iter); } else { ++l_Iter; } } } If any shell flies outside the screen bounding box, its instance is erased from the collection and the renderer no longer worries about allocating memory for an irrelevant item. To give you an idea of how that happens, here is a snippet that shows how the RenderScreen function handles the current ammo set: if (!m_ammoCollection.empty()) { for (auto shell = m_ammoCollection.begin(); shell != m_ammoCollection.end(); shell++) { if (!(*shell)->IsFriendly) { (*shell)->Render(); } else { GameBear->RenderShell((*shell)->Position, (*shell)->Rotation); } } }   Conclusion Element interaction is a core part of the FallFury experience. Separate handlers are implemented for each of them to ensure maximum flexibility when it comes to adding or removing components without breaking major parts of the code-base. Handling is mainly accomplished in the Update loop by iterating through registered entity sets, such as ammo, and verifying whether an action should be taken. Be cautious when implementing this kind of scenario with large entities and data sets—having multiple loops running simultaneously might tax machine performance, especially on low-power configurations such as ARM. ]]> https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-8-Element-Interaction Element InteractionDuring the gameplay multiple entities interact with each other to make the gaming experience what it is. The bear collides with obstacles and collects buttons, monsters shoot shells that can fly off-screen or hit the bear—all this is possible with the help of the basic collision detection techniques that are implemented in FallFury. Check out the video for this article at https://channel9.msdn.com/Series/FallFury/Part-8-Element-Interaction . For a complete, offline version of this series, you may download a nicely formatted PDF of all the articles. ButtonsButtons are bonus-boosters that can be placed by the level designer anywhere on the screen in game mode. These are relatively small entities, which are displaced vertically with each cycle of the Update loop and move in the opposite direction, but with the same velocity, as the main character. Looking at the Update function in the GamePlayScreen class, you will notice this call: UpdateButtons(); UpdateButtons can be considered the button manager function responsible for removing the collected buttons from the rendering stack, counting them, and checking for a button collision when the bear is in close proximity. The implementation looks like this: void GamePlayScreen::UpdateButtons() { Windows::Foundation::Rect livingEntityBoundingBox = GameBear-&gt;GetBoundingBox(); for (auto button = m_buttons.begin(); button != m_buttons.end();) { (*button)-&gt;Position.x = (*button)-&gt;PixelDiff &#43; LoBoundX; (*button)-&gt;Position.y -= GameBear-&gt;Velocity.y; if (Geometry::IsInProximity(GameBear-&gt;Position,(*button)-&gt;Position, 100)) { Windows::Foundation::Rect obstacleRect = (*button)-&gt;GetBoundingBox(); if (livingEntityBoundingBox.IntersectsWith(obstacleRect)) { AudioManager::AudioEngineInstance.StopSoundEffect(Coin); AudioManager::AudioEngineInstance.PlaySoundEffect https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-8-Element-Interaction Wed, 23 Jan 2013 23:57:25 GMT https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-8-Element-Interaction Brian Peek, Clint Rutkas, Dan Fernandez, Den Delimarsky, Rick Barraza Brian Peek, Clint Rutkas, Dan Fernandez, Den Delimarsky, Rick Barraza 0 https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-8-Element-Interaction/RSS C# C++ DirectX Windows Store App Fall Fury: Part 7 - Animations Animations & Item Transitions FallFury relies on a lot of dynamic content. As you already aware of how SpriteBatch is invoked inside the FallFury rendering stack, this article focuses on how dynamic activities are handled on existing textures and entities. If you need a quick look at what was already covered, refer to Part 3 of the series. Check out the video for this article at https://channel9.msdn.com/Series/FallFury/Part-7-Animations . For a complete, offline version of this series, you may download a nicely formatted PDF of all the articles. Menu Screen The first animated element shown in the menu screen is the bear, which is positioned in the top half of the viewport. Notice that the bear moves its paws as well as moving across the screen: image The bear is implemented in the GameBear class and is the normal playable entity that is invincible when animated outside the scope of the gameplay screen. Its full body image is composed of four textures: Microsoft::WRL::ComPtr<ID3D11Texture2D> m_head; Microsoft::WRL::ComPtr<ID3D11Texture2D> m_leftPaw; Microsoft::WRL::ComPtr<ID3D11Texture2D> m_rightPaw; Microsoft::WRL::ComPtr<ID3D11Texture2D> m_body // Exposed through LivingEntity; Each of these textures is internally dependent on the coupled float rotation and position values passed to the sprite batch in the host container (the parent screen): HostContainer->CurrentSpriteBatch->Draw( m_rightPaw.Get(), m_rightPawPosition, PositionUnits::DIPs, float2(522.0f, 141.0f) * Scale, SizeUnits::Pixels, m_shading, m_rightPawRotation - 0.5f); HostContainer->CurrentSpriteBatch->Draw( m_body.Get(), Position, PositionUnits::DIPs, float2(400.0f, 400.0f) * Scale, SizeUnits::Pixels, m_shading, Rotation); HostContainer->CurrentSpriteBatch->Draw( m_leftPaw.Get(), m_leftPawPosition, PositionUnits::DIPs, float2(522.0f, 141.0f) * Scale, SizeUnits::Pixels, m_shading, m_leftPawRotation + 0.5f); Let’s take a look at how the position and rotation values are modified. All item animations are performed with the help of timers set to brief intervals in which the values are cycled through two value exchange operations. Here is a snippet taken from inside the Update method in the GameBear class that is responsible for bear arm movement: if (m_armRotationTimer < 0.6f) { m_rightPawRotation -= 0.005f; m_leftPawRotation += 0.005f; } else if (m_armRotationTimer > 0.6f && m_armRotationTimer < 1.2f) { m_rightPawRotation += 0.005f; m_leftPawRotation -= 0.005f; } else { m_rightPawRotation = 0.0f; m_leftPawRotation = 0.0f; m_armRotationTimer = 0.0f; } m_armRotationTimer is a float value that is initially set to 0.0f. In the Update loop and increments each iteration by the value of timeDelta, which represents the time difference between two loop cycles. As this value is less than 600 milliseconds (0.6 seconds), the right paw rotation is incremented and the left paw rotation decremented. The difference in the value adjustment direction is caused by the fact that one paw is rotated clockwise and the other is rotated counterclockwise. Once the timer tracks a value above 600 milliseconds but below than 1200 milliseconds, the process reverses and the paws rotate in the opposite direction. After 1.2 seconds, the timer resets, as does the rotation. Since this rotation is automated, GameBear->Update is called in the menu screen: m_showBear->Update(timeTotal, timeDelta, float2(Manager->m_windowBounds.Width / 2, Manager->m_windowBounds.Height / 2)); Outside the context of the bear update cycle, there is a similar timed mechanism used to randomly move the bear across the screen: if (m_positionYAdj == 0.0f) { m_positionYAdj = RandFloat(0.1f, 1.2f); m_positionXAdj = RandFloat(-1.0f, 1.0f); } if (m_positionTimer < 4.0f) { m_showBear->Position.x += m_positionXAdj; m_showBear->Position.y += m_positionYAdj; m_showBear->Rotation += 0.001f; m_showBear->Scale += 0.0008f; m_showMonster->Scale += 0.002f; } else if (m_positionTimer > 4.0f && m_positionTimer < 8.0f) { m_showBear->Position.x -= m_positionXAdj; m_showBear->Position.y -= m_positionYAdj; m_showBear->Rotation -= 0.001f; m_showBear->Scale -= 0.0008f; } else { m_positionYAdj = 0.0f; m_positionTimer = 0.0f; } The X and Y adjustments are randomly generated and for the duration of a single timer cycle (in this case, 4 seconds) the bear’s horizontal and vertical positions are adjusted using those values. The rotation and scale are minimally adjusted to create a 3D motion effect. Because the displacement is minimal, the bear is always visible and does not move much outside the viewport. There is also a flying monster animation in the main menu screen. Monster creation happens on top of the same instance that is replaced when an initial monster flies out of bounds: m_showMonster->Position.y -= m_showMonster->Velocity.y; if (m_showMonster->Position.y < -m_showMonster->Size.y) { CreateNewMonster(); }   When a new monster is created, a random monster type is selected and its position on the X axis is randomized. The Y position is set to be right under the bottom screen boundary: void MenuScreen::CreateNewMonster() { m_showMonster = ref new Monster(this, (MonsterType)(rand() % (int)MonsterType::MT_CANDYLAND_E), true); m_showMonster->Scale = 0.3f; m_showMonster->Velocity.y = 1.0f; m_showMonster->Load(); m_showMonster->Position = float2(RandFloat(LoBoundX, HiBoundX), Manager->m_windowBounds.Height + m_showMonster->Size.y * m_showMonster->Scale); } Monster scaling is done on the same timed loop as the bear. The results look like this: image Gameplay Screen Bear The gameplay screen carries the most animations in FallFury, including animations related to ammo displacement, monster movement paths, power-up animations, and secondary game character animations that are triggered in special cases such as character death. Let’s start with character entrance. When the game begins, the teddy bear falls into the screen and stops at a specific point close to the top boundary of the gameplay screen. Once that transition is complete, the bear is no longer vertically displaced: if ((GameBear->Position.y / HiBoundY) < 0.19f) { GameBear->Position.y += GameBear->Velocity.y * (3.2f); }   If the limit is not hit, the original bear velocity is multiplied by a fixed value, after which the condition is ignored for the rest of the gameplay. Let’s now take a look at what happens when an enemy shell kills the bear. Generally, when the main character is killed, there is not much sense in maintaining other in-game activities. In FallFury, a killed bear results in a time freeze—the fall stops and the monsters are no longer shooting or moving. Not only that, but the bear is also flipped on its back: image In the Update loop, the position for the paws and the head are adjusted for the new body texture layout: if (IsDead) { if (m_armRotationTimer < 1.0f) { m_rightPawRotation += 0.001f; m_leftPawRotation -= 0.001f; } else if (m_armRotationTimer > 1.0f && m_armRotationTimer < 2.0f) { m_rightPawRotation -= 0.001f; m_leftPawRotation += 0.001f; } else { m_rightPawRotation = 0.0f; m_leftPawRotation = 0.0f; m_armRotationTimer = 0.0f; } m_rightPawPosition = Position + float2(40.0f, -50.0f) * Scale; m_leftPawPosition = Position + float2(10.0f, 150.0f) * Scale; m_headPosition = (Position - float2(-160.0f, 0.0f) * Scale); } The proper textures are assigned via the Kill method: void Bear::Kill() { IsDead = true; Rotation = -1.0f; m_head = m_deadHead; m_body = m_deadBody; m_leftPaw = m_deadLeftArm; m_rightPaw = m_deadRightArm; } The bear will continue falling as long as StopBackground in GamePlayScreen is called: void GamePlayScreen::StopBackground() { m_isBackgroundMoving = false; } This will cause the internal state check to fail in the Update loop, sending the bear off screen limits. Once the bear completes the fall, the state is set to GS_GAME_OVER: if (!m_isBackgroundMoving) { if (GameBear->Position.y > m_screenSize.y) { Manager->CurrentGameState = GameState::GS_GAME_OVER; } else { GameBear->Position.y += GameBear->Velocity.y * 1.5f; } } Monsters Monsters, on the other hand, are being constantly moved during the duration of the game. Their basic displacement is performed by MoveMonsters: void GamePlayScreen::MoveMonsters(float timeTotal ,float timeDelta) { for (auto monster = m_monsters.begin(); monster != m_monsters.end();) { Monster^ currentMonster = (*monster); if ((currentMonster->Position.y - GameBear->Position.y) < -Manager->m_renderTargetSize.Height / 2) { monster = m_monsters.erase(monster); } else { currentMonster->Velocity.y = GameBear->Velocity.y; currentMonster->Update(timeTotal, timeDelta, GameBear->Position, GetScreenBounds()); CheckForCollisionWithAmmo(currentMonster); ++monster; } } } This method adjusts the monster position relative to the bear: image The zig-zag like motion is defined in the Monster class in the Update method: float adjustment = 0.0f; adjustment = m_goingRight ? Position.x + Velocity.x : Position.x - Velocity.x; if (adjustment >= (HostContainer->LoBoundX + (Size.x * Scale) / 2.0f) && adjustment <= (HostContainer->HiBoundX - (Size.x * Scale) / 2.0f)) { Position.x = adjustment; } else { m_goingRight = !m_goingRight; }   The snippet above determines the direction in which the enemy has to move depending on which screen boundary is hit first. While the monster is active and is visible, its vertical adjustment is performed in a timed loop, like this: m_jumpingTimer += timeDelta; if (m_jumpingTimer > 0.0f && m_jumpingTimer < 1.0f) { Position.y -= 1.0f; } else if (m_jumpingTimer >= 1.0f && m_jumpingTimer < 2.0f) { Position.y += 1.0f; } else { m_jumpingTimer = 0.0f; } Here you can either use the Y velocity or introduce a static value. The only condition has to be a number low enough that the monster does not leave the screen, which would prevent the bear from being able to kill it. When the monster is killed, it flies out by following an arch-like path: image The “death arc” is implemented via another timer: Position.x += Velocity.y * 1.3f; if (m_deathArcTimer > 0.4f) { Position.y += Velocity.y; if (Scale > 0.1f) Scale -= 0.01f; } else { Position.y -= Velocity.y; Scale += 0.01f; m_deathArcTimer += timeDelta; }   Regardless of the monster position, the horizontal displacement is positive and the entity moves to the right. For 400 milliseconds its vertical position is decreased, moving the texture up, and the scale is also adjusted to create the proximity effect. After this time interval, the monster drops out of the screen boundaries. As previously mentioned, each monster is composed of three cycled textures, which are loaded and stored in three ID3D11Texture2D containers: Microsoft::WRL::ComPtr<ID3D11Texture2D> m_spriteA; Microsoft::WRL::ComPtr<ID3D11Texture2D> m_spriteB; Microsoft::WRL::ComPtr<ID3D11Texture2D> m_spriteC;   Each of these is assigned to the main body texture container every 300 milliseconds, replacing the previously assigned asset: m_stateChangeTimer += timeDelta; if (m_stateChangeTimer < 0.3f) { m_body = m_spriteA; } else if (m_stateChangeTimer > 0.3f && m_stateChangeTimer < 0.6f) { m_body = m_spriteB; } else if (m_stateChangeTimer > 0.6f && m_stateChangeTimer < 0.9f) { m_body = m_spriteC; } else if (m_stateChangeTimer > 0.9f) { m_stateChangeTimer = 0.0f; }   This cycle can be disabled when the monster is not active. Ammo There are different types of ammo used in the game, and each behaves in its own way. The stock ammo type is a plasma ball. The default shooting behavior releases a shell when the user taps anywhere on the screen (other than the pause button area). Given the texture of the shell, when it is released the tail must be oriented towards the bear at an angle equal to the one created by the bear and the target position. To get a better idea, take a look at the images below: image image In the image on the left, the player tapped at the bottom of the screen. In the one on the right, the player tapped at the right edge of the screen. The shell accordingly rotates depending on the tapped position. To get a better understanding of how the rotation is performed, imagine the XY coordinate grid with the bear located at the intersection of the axes: image Thinking back to trigonometry, notice the triangle formed by the shell and the bear origin point: image Remember also the trig concept of quadrants: image The quadrant in which the shell is located determines how the angle is calculated and the tail rotated. If the shell is in quadrant 2 or 3, calculate the rotation radians by following this algorithm: 1. Find the hypotenuse from the X and Y components of the velocity, which can be calculated by finding the difference between the bear and the position of the tap. To do this, us the well-known Pythagorean theorem: image The hypotenuse formula can be deduced from the formula above and is the square root of the sum of the velocity component squares: image 2. Once calculated, it is necessary to find the sine of the target angle. The value can be obtained by dividing the Y component of the velocity by the hypotenuse. 3. Find the angle by calculating the arcsine from the resultant sine value. This will return the final angle in radians. That said, for shells launched in quadrants 1 or 4, there is one extra step that needs to be performed. In addition to the rotation value obtained from the steps listed above, the rotation should be incremented by the radian value of a 180-degree angle minus twice the rotation value previously obtained. This ensures that the tail is correctly flipped relative to the axis origin. In C++, the implementation is done inside the AmmoItem class. For flexibility purposes, it triggers inside the Update loop—that way, it is possible to modify the trajectory of the shell and not worry about turning it again manually after launch: if ((Velocity.x > 0 && Velocity.y > 0) || (Velocity.x > 0 && Velocity.y <0)) { Rotation = CalculateRadians(Velocity); Rotation += CalculateRadiansFromAngle(180) - 2 * Rotation; } else { Rotation = CalculateRadians(Velocity); } CalculateRadians is the method that transforms the velocity components in a rotation value. It is located in the BasicMath.h helper: inline float CalculateRadians(float2 velocity) { float hypothenuse = sqrt(velocity.x * velocity.x + velocity.y * velocity.y); float sine = velocity.y / hypothenuse; float angle = asin(sine); return angle; };   There is a potential problem with the implementation above. As the user taps on different parts of the screen, the X and Y components are different, each resulting in a different hypotenuse. As the target is set, the shell flies faster the further away from the bear the user taps. To avoid this, the triangle legs should be normalized to a near-constant value: Take a look at the ShootAtTarget function in the Bear class: void Bear::ShootAtTarget(float2 lastTargetTrace) { OnPulledTrigger(Position.x, Position.y, GetVelocityLegs(lastTargetTrace).x, GetVelocityLegs(lastTargetTrace).y, CurrentDamage, IsFriendly, false, HostContainer->CurrentSpriteBatch); }   Notice that the triangle legs are not passed as a raw value, but are proxied through GetVelocityLegs, which forces the resulting vector to be produced from a constant triangle with the velocity constant at 10 pixels per iteration: float2 LivingEntity::GetVelocityLegs(float2 lastTargetTrace) { float bottomLeg = 0.0f; float sideLeg = (Position.y - lastTargetTrace.y) / 100.0f; bottomLeg = (Position.x - lastTargetTrace.x) / 100.0f; float requiredVelocity = 10.0f; float hypothenuse = sqrt(bottomLeg * bottomLeg + sideLeg * sideLeg); float proportionalX = 0.0f; float proportionalY = 0.0f; proportionalX = (requiredVelocity * bottomLeg) / hypothenuse; proportionalY = (sideLeg < 0.0f ? -1 : 1) * sqrt(requiredVelocity * requiredVelocity - proportionalX * proportionalX); return float2(proportionalX,proportionalY); }   For ammo that does not have a visual rotation dependency, such as the plasma ball, simply increment the rotation to make the thrown item continuously spin: if (Type == PowerupType::PLASMA_BALL) { if ((Velocity.x > 0 && Velocity.y > 0) || (Velocity.x > 0 && Velocity.y <0)) { Rotation = CalculateRadians(Velocity); Rotation += CalculateRadiansFromAngle(180) - 2 * Rotation; } else { Rotation = CalculateRadians(Velocity); } } else { Rotation += 0.2f; }   Conclusions FallFury mostly relies on sprite-based animations in which there are several textures cycled through in order to create the desired dynamic effect. These are not really hard to build, given that there is a possibility to integrate them in a timed loop. Be aware, however, that with slower machines the timing might be off and the time delta value between loops might be higher. In that case the sprite cycling will not be as smooth as it should be, which is why it’s important to perform animation testing on a variety of hardware with different OS loads. ]]> https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-7-Animations Animations &amp; Item TransitionsFallFury relies on a lot of dynamic content. As you already aware of how SpriteBatch is invoked inside the FallFury rendering stack, this article focuses on how dynamic activities are handled on existing textures and entities. If you need a quick look at what was already covered, refer to Part 3 of the series. Check out the video for this article at https://channel9.msdn.com/Series/FallFury/Part-7-Animations . For a complete, offline version of this series, you may download a nicely formatted PDF of all the articles. Menu ScreenThe first animated element shown in the menu screen is the bear, which is positioned in the top half of the viewport. Notice that the bear moves its paws as well as moving across the screen: The bear is implemented in the GameBear class and is the normal playable entity that is invincible when animated outside the scope of the gameplay screen. Its full body image is composed of four textures: Microsoft::WRL::ComPtr&lt;ID3D11Texture2D&gt; m_head; Microsoft::WRL::ComPtr&lt;ID3D11Texture2D&gt; m_leftPaw; Microsoft::WRL::ComPtr&lt;ID3D11Texture2D&gt; m_rightPaw; Microsoft::WRL::ComPtr&lt;ID3D11Texture2D&gt; m_body // Exposed through LivingEntity; Each of these textures is internally dependent on the coupled float rotation and position values passed to the sprite batch in the host container (the parent screen): HostContainer-&gt;CurrentSpriteBatch-&gt;Draw( m_rightPaw.Get(), m_rightPawPosition, PositionUnits::DIPs, float2(522.0f, 141.0f) * Scale, SizeUnits::Pixels, m_shading, m_rightPawRotation - 0.5f); HostContainer-&gt;CurrentSpriteBatch-&gt;Draw( m_body.Get(), Position, PositionUnits::DIPs, float2(400.0f, 400.0f) * Scale, SizeUnits::Pixels, m_shading, Rotation); HostContainer-&gt;CurrentSpriteBatch-&gt;Draw( m_leftPaw.Get(), m_leftPawPosition, PositionUnits::DIPs, float2(522.0f, https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-7-Animations Wed, 23 Jan 2013 23:57:22 GMT https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-7-Animations Brian Peek, Clint Rutkas, Dan Fernandez, Den Delimarsky, Rick Barraza Brian Peek, Clint Rutkas, Dan Fernandez, Den Delimarsky, Rick Barraza 0 https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-7-Animations/RSS C# C++ DirectX Windows Store App Fall Fury: Part 6 - Rendering Level Elements Rendering Level Elements In the previous article, you learned how to build level XML files in order to create playable levels. This article discusses how the internal parser works and how XML nodes become items on the game screen.  Check out the video for this article at https://channel9.msdn.com/Series/FallFury/Part-6-Rendering-Level-Elements.  For a complete, offline version of this series, you may download a nicely formatted PDF of all the articles. Project Interop – The C# Parser Thanks to classes such as XmlSerializer and XDocument, parsing XML in .NET Framework is not a complicated task. Similarly, in the WinRT world there are alternatives such as Windows::Data::Xml::Dom. That being said, using the parser skeleton in C# this project leverages the existing codebase, adapting it to the specific level reading needs. Start by creating a new WinRT project that is the part of the existing solution. Make sure that you create a Windows Runtime Component: clip_image002 There are major differences between the .NET and WinRT stacks, especially when it comes to building code that can be invoked from any potential WinRT project type, as is the case here. Make sure that the output of the newly created project is a Windows Runtime Component (WinMD file): clip_image004 The XMLReader project reads much more than the level data—it also manages internal XML metadata such as user scores. This article, however, focuses only on level-related aspects of the engine. Reader is the one core class used here. It contains the ReadXml method, which receives the file name and the type of the XML file to be read. Regardless of the name, the XML file type determines the parsing rules, the root lookup location, and the produced output. The tier (level set) and individual level data are stored internally in the application folder, and the score metadata is outside the sandbox in the application data folder: async Task<Object> ReadXml(string fileName, XmlType type) { StorageFile file = null; StorageFolder folder = null; if (type == XmlType.LEVEL || type == XmlType.TIERS) { folder = Windows.ApplicationModel.Package.Current.InstalledLocation; folder = await folder.GetFolderAsync("Levels"); } else if (type == XmlType.HIGHSCORE) { folder = ApplicationData.Current.LocalFolder; folder = await folder.GetFolderAsync("Meta"); } file = await folder.GetFileAsync(fileName); Object returnValue = null; string data; using (IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read)) { using (Stream inStream = Task.Run(() => readStream.AsStreamForRead()).Result) { using (StreamReader reader = new StreamReader(inStream)) { data = reader.ReadToEnd(); } } } if (type == XmlType.LEVEL) { returnValue = ExtractLevelData(data); } else if (type == XmlType.HIGHSCORE) { returnValue = ExtractScoreData(data); } else if (type == XmlType.TIERS) { returnValue = ExtractTierData(data); } return returnValue; } Before the level data is extracted, FallFury needs to know about the existing tiers pointing to those levels. That’s where ExtractTierData, an internal method that accepts a raw XML string and return a TierSet instance, comes in: public sealed class TierSet { public Tier[] Tiers { get; set; } } A Tier class has the following structure: public sealed class Tier { public string Name { get; set; } public string[] LevelNames { get; set; } public string[] LevelFiles { get; set; } } I am using the most fundamental types – arrays instead of generic collections, to maximize the portability of the code. The ExtractTierData method handles the XML-to-Object transformation: TierSet ExtractTierData(string tierString) { TierSet set = new TierSet(); XDocument document = XDocument.Parse(tierString); set.Tiers = new Tier[document.Root.Elements().Count()]; int tierCounter = 0; foreach (XElement element in document.Root.Elements()) { Tier tier = new Tier(); tier.Name = element.Attribute("name").Value; tier.LevelFiles = new string[element.Elements("level").Count()]; tier.LevelNames = new string[element.Elements("level").Count()]; int count = 0; foreach (XElement lElement in element.Elements("level")) { tier.LevelFiles[count] = lElement.Attribute("file").Value; tier.LevelNames[count] = lElement.Attribute("name").Value; count++; } set.Tiers[tierCounter] = tier; tierCounter++; } return set; } I am running a coupled array block here, utilizing one array for level names and another for file locations. This is a very basic implementation of a key-value pair that depends on code-based coupling. ExtractTierData, however, is not exposed publicly and the C++ layer of FallFury will not access it because TierSet is not exposed through a compatible async method. Looking back at ReadXml, might seem like the answer to this problem. But a Task<Object> is not an interop-compatible type, which means I use ReadXmlAsync, which proxies the call through an IAsyncOperation: public IAsyncOperation<Object> ReadXmlAsync(string filename, XmlType type) { return (IAsyncOperation<Object>)AsyncInfo.Run((CancellationToken token) => ReadXml(filename, type)); } AsyncInfo.Run starts a WinRT async operation and handles the returned result, regardless of the selected file path or type. Level-based data is extracted in a similar manner to the tier data. The difference lies in the used internal models, as well as the node reading order: Level ExtractLevelData(string levelString) { XDocument document = XDocument.Parse(levelString); Level level = new Level(); level.LevelMeta = new Meta(); level.LevelMeta.Score = Convert.ToInt32(document.Root.Element("meta").Attribute("score").Value); level.LevelMeta.ButtonPrice = Convert.ToInt32(document.Root.Element("meta").Attribute("buttonPrice").Value) level.LevelMeta.LevelType = (LevelType)Convert.ToInt32(document.Root.Attribute("type").Value); int count = document.Root.Element("obstacles").Elements().Count(); level.Obstacles = new Obstacle[count]; count = 0; foreach (XElement element in document.Root.Element("obstacles").Elements()) { Obstacle obstacle = new Obstacle(); obstacle.HealthDamage = Convert.ToSingle(element.Attribute("healthDamage").Value); obstacle.InflictsDamage = Convert.ToBoolean(element.Attribute("inflictsDamage").Value); obstacle.Rotation = Convert.ToSingle(element.Attribute("rotation").Value); obstacle.Scale = Convert.ToSingle(element.Attribute("scale").Value); obstacle.X = Convert.ToSingle(element.Attribute("x").Value); obstacle.Y = Convert.ToSingle(element.Attribute("y").Value); obstacle.Type = (ObstacleType)Convert.ToInt32(element.Attribute("type").Value); level.Obstacles[count] = obstacle; count++; } count = document.Root.Element("monsters").Elements().Count(); level.Monsters = new Monster[count]; count = 0; foreach (XElement element in document.Root.Element("monsters").Elements()) { Monster monster = new Monster(); monster.CriticalDamage = Convert.ToSingle(element.Attribute("criticalDamage").Value); monster.Damage = Convert.ToSingle(element.Attribute("damage").Value); monster.DefaultAmmo = Convert.ToInt32(element.Attribute("defaultAmmo").Value); monster.MaxHealth = Convert.ToSingle(element.Attribute("maxHealth").Value); monster.X = Convert.ToSingle(element.Attribute("x").Value); monster.Y = Convert.ToSingle(element.Attribute("y").Value); monster.VelocityX = Convert.ToSingle(element.Attribute("velocityX").Value); monster.Lifetime = Convert.ToSingle(element.Attribute("lifetime").Value); monster.Type = (MonsterType)Convert.ToInt32(element.Attribute("type").Value); monster.Bonus = Convert.ToInt32(element.Attribute("bonus").Value); monster.Scale = Convert.ToSingle(element.Attribute("scale").Value); level.Monsters[count] = monster; count++; } count = document.Root.Element("buttons").Elements().Count(); level.Buttons = new Button[count]; count = 0; foreach (XElement element in document.Root.Element("buttons").Elements()) { Button button = new Button(); button.X = Convert.ToSingle(element.Attribute("x").Value); button.Y = Convert.ToSingle(element.Attribute("y").Value); level.Buttons[count] = button; count++; } count = document.Root.Element("powerups").Elements().Count(); level.Powerups = new Powerup[count]; count = 0; foreach (XElement element in document.Root.Element("powerups").Elements()) { Powerup powerup = new Powerup(); powerup.X = Convert.ToSingle(element.Attribute("x").Value); powerup.Y = Convert.ToSingle(element.Attribute("y").Value); powerup.Category = (PowerupCategory)Convert.ToInt32(element.Attribute("category").Value); powerup.Type = (PowerupType)Convert.ToInt32(element.Attribute("type").Value); powerup.Lifespan = Convert.ToSingle(element.Attribute("lifespan").Value); powerup.Effect = Convert.ToSingle(element.Attribute("effect").Value); level.Powerups[count] = powerup; count++; } Bear bear = new Bear(); XElement bearElement = document.Root.Element("bear"); bear.CriticalDamage = Convert.ToSingle(bearElement.Attribute("criticalDamage").Value); bear.Damage = Convert.ToSingle(bearElement.Attribute("damage").Value); bear.DefaultAmmo = Convert.ToInt32(bearElement.Attribute("defaultAmmo").Value); bear.MaxHealth = Convert.ToSingle(bearElement.Attribute("maxHealth").Value); bear.StartPosition = Convert.ToSingle(bearElement.Attribute("startPosition").Value); bear.Velocity = Convert.ToSingle(bearElement.Attribute("velocity").Value); level.GameBear = bear; return level; } As a result, the Level instance has an internal counterpart in the C++ project: public sealed class Level { public Bear GameBear { get; set; } public Meta LevelMeta { get; set; } public Obstacle[] Obstacles { get; set; } public Monster[] Monsters { get; set; } public Button[] Buttons { get; set; } public Powerup[] Powerups { get; set; } } From C# to C++ - Leveraging the WinRT Component At this point, the C#-based WinRT component is complete and can be integrated into the C++ project. This can be done in two ways: either by adding a reference to the project itself or by adding a reference to the generated WinMD file. Both methods will ultimately produce the same output, but it’s easier to debug and modify coupled projects on the go, so I went with the first option. To add a reference to an internal Windows Runtime Component project, right click on the C++ project in Solution Explorer and select Properties. You will see a dialog like this: clip_image006 Select the Common Properties node in the tree on the left and open the Framework and References page: clip_image008 In the sample screen capture above, the FallFury.XMLReader project is already added as a reference. For a new project, simply click on Add New Reference and add any compatible project or third-party extension. As soon as the reference is added, the publicly exposed methods can be accessed. In DirectXPage.cpp I have a method called LoadLevelData that allows me to load the list of the registered levels from core.xml as well as build the visual tree for the menu items, whichallows players to select a level: void DirectXPage::LoadLevelData() { Coding4Fun::FallFury::XMLReader::Reader^ reader = ref new Coding4Fun::FallFury::XMLReader::Reader(); Windows::Foundation::IAsyncOperation<Platform::Object^>^ result = reader->ReadXmlAsync("core.xml", Coding4Fun::FallFury::XMLReader::Models::XmlType::TIERS); result->Completed = ref new AsyncOperationCompletedHandler<Platform::Object^>(this, &DirectXPage::OnLevelLoadCompleted); } Following the normal asynchronous pattern, as well as the structure of the method exposed in the Reader class, I am calling ReadXmlAsync and getting the result in OnLevelLoadCompleted when the operation reaches its final stage. It is worth mentioning that the associated AsyncOperationCompletedHandler is invoked even when the reading fails; therefore, the invocation of that callback does not on its own mean that the necessary data is obtained: Here is what happens when OnLevelLoadCompleted is called: void DirectXPage::OnLevelLoadCompleted(IAsyncOperation<Platform::Object^> ^op, AsyncStatus s) { if (s == AsyncStatus::Completed) { auto set = (Coding4Fun::FallFury::XMLReader::Models::TierSet^)op->GetResults(); auto tiers = set->Tiers; int levelCounter = 0; for (auto tier = tiers->begin(); tier != tiers->end(); tier++) { StackPanel^ panel = ref new StackPanel(); TextBlock^ levelTierTitle = ref new TextBlock(); levelTierTitle->Text = (*tier)->Name; levelTierTitle->Style = (Windows::UI::Xaml::Style^)Application::Current->Resources->Lookup("LevelSelectTierItemText"); levelTierTitle->RenderTransform = ref new TranslateTransform(); panel->Children->Append(levelTierTitle); levelNames = (*tier)->LevelNames; auto levelFiles = (*tier)->LevelFiles; int max = levelNames->Length; for(int i = 0; i < max; i++) { MenuItem^ item = ref new MenuItem(); item->Tag = levelCounter; item->Label = levelNames[i]; item->HorizontalAlignment = Windows::UI::Xaml::HorizontalAlignment::Left; item->OnButtonSelected += ref new MenuItem::ButtonSelected(this, &DirectXPage::OnLevelButtonSelected); item->RenderTransform = ref new TranslateTransform(); m_renderer->Levels.Insert(levelCounter,levelFiles[i]); panel->Children->Append(item); levelCounter++; } stkLevelContainer->Items->Append(panel); } } } Here, AsyncStatus can also be Cancelled or Error, so checking for Complete ensures that the expected result is processed further inside the context of the callback. As the returned TierSet exposes the Tiers array, I am simply iterating through each of the existing items to create independent tier blocks, grouped in StackPanel elements, coupled with level-specific MenuItem instances that present the user with a choice of playing a given level. The level ID is carried in the Tag property and it will be used to identify the selected button when DirectXPage::OnLevelButtonSelected is triggered: Reading Level-specific Data Level data is read in the GamePlayScreen once the selected menu button passes the name and level identifiers. The LoadLevelXml method is called as the screen begins to load, preparing all assets for the start of the game session: void GamePlayScreen::LoadLevelXML() { Coding4Fun::FallFury::XMLReader::Reader^ reader = ref new Coding4Fun::FallFury::XMLReader::Reader(); Platform::String^ LevelName = Manager->Levels.Lookup(StaticDataHelper::CurrentLevelID); Windows::Foundation::IAsyncOperation<Platform::Object^>^ result = reader->ReadXmlAsync(LevelName, Coding4Fun::FallFury::XMLReader::Models::XmlType::LEVEL); result->Completed = ref new AsyncOperationCompletedHandler<Platform::Object^>(this, &GamePlayScreen::OnLevelLoadCompleted); } The selected ID passes from the menu screen to the game screen through CurrentLevelID, an intermediary value preserved in a StaticDataHelper class. The level file name is looked up based on the ID and then passed to ReadXmlAsync with the XmlType set to LEVEL. When the load completes, OnLevelLoadCompleted is invoked, and an additional helper class— LevelDataLoader—sets up the game components based on the received data: void GamePlayScreen::OnLevelLoadCompleted(IAsyncOperation<Platform::Object^> ^op, AsyncStatus s) { if (s == AsyncStatus::Completed) { InitializeSpriteBatch(); m_loader = ref new BasicLoader(Manager->m_d3dDevice.Get(), Manager->m_wicFactory.Get()); CreateBear(); LevelDataLoader^ loader = ref new LevelDataLoader((Coding4Fun::FallFury::XMLReader::Models::Level^)op->GetResults(), this); loader->SetupBear(GameBear); loader->SetupObstacles(m_obstacles); loader->SetupMonsters(m_monsters); loader->SetupButtons(m_buttons, m_buttonPrice); loader->SetupPowerups(m_powerups); m_currentLevelType = (LevelType) loader->CurrentLevel->LevelMeta->LevelType; StaticDataHelper::CurrentLevel = loader->CurrentLevel; StaticDataHelper::ButtonsTotal = loader->CurrentLevel->Buttons->Length; LoadTextures(); CreateMonster(); CreatePowerups(); IsLevelLoaded = true; GameBear->TurnRight(); m_particleSystem.CreatePreCachedParticleSets(); LoadSounds(); } } Each object is separated in its own method, such as SetupBear or SetupObstacles. SetupBear, for example, transforms the exposed managed Bear model to a native C++ Characters::Bear one: void LevelDataLoader::SetupBear(Bear ^gameBear) { gameBear->Position = float2(GetXPosition(CurrentLevel->GameBear->StartPosition), 0); gameBear->MaxHealth = CurrentLevel->GameBear->MaxHealth; gameBear->CurrentHealth = CurrentLevel->GameBear->MaxHealth; gameBear->CurrentDamage = CurrentLevel->GameBear->Damage; gameBear->Velocity.y = CurrentLevel->GameBear->Velocity; gameBear->MaxCriticalDamage = CurrentLevel->GameBear->CriticalDamage; gameBear->Rotation = 0.0f; } Conclusion Mixing C# and C++ components is not a complicated process. Nonetheless, it comes with specific restrictions and considerations, such as the format of the publicly exposed asynchronous calls. The above C#-based level loading engine highlights the fact that WinRT interoperability allows you to leverage the languages you know best in order to efficiently accomplish project tasks. ]]> https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-6-Rendering-Level-Elements Rendering Level ElementsIn the previous article, you learned how to build level XML files in order to create playable levels. This article discusses how the internal parser works and how XML nodes become items on the game screen. Check out the video for this article at https://channel9.msdn.com/Series/FallFury/Part-6-Rendering-Level-Elements. For a complete, offline version of this series, you may download a nicely formatted PDF of all the articles. Project Interop – The C# ParserThanks to classes such as XmlSerializer and XDocument, parsing XML in .NET Framework is not a complicated task. Similarly, in the WinRT world there are alternatives such as Windows::Data::Xml::Dom. That being said, using the parser skeleton in C# this project leverages the existing codebase, adapting it to the specific level reading needs. Start by creating a new WinRT project that is the part of the existing solution. Make sure that you create a Windows Runtime Component: There are major differences between the .NET and WinRT stacks, especially when it comes to building code that can be invoked from any potential WinRT project type, as is the case here. Make sure that the output of the newly created project is a Windows Runtime Component (WinMD file): The XMLReader project reads much more than the level data—it also manages internal XML metadata such as user scores. This article, however, focuses only on level-related aspects of the engine. Reader is the one core class used here. It contains the ReadXml method, which receives the file name and the type of the XML file to be read. Regardless of the name, the XML file type determines the parsing rules, the root lookup location, and the produced output. The tier (level set) and individual level data are stored internally in the application folder, and the score metadata is outside the sandbox in the application data folder: async Task&lt;Object&gt; ReadXml(string fileName, XmlType type) { StorageFile file = null; Stor https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-6-Rendering-Level-Elements Wed, 23 Jan 2013 23:57:17 GMT https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-6-Rendering-Level-Elements Brian Peek, Clint Rutkas, Dan Fernandez, Den Delimarsky, Rick Barraza Brian Peek, Clint Rutkas, Dan Fernandez, Den Delimarsky, Rick Barraza 0 https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-6-Rendering-Level-Elements/RSS C# C++ DirectX Windows Store App Fall Fury: Part 5 - Creating Levels Creating Levels One of the goals set when developing FallFury was making the game extensible in regards to playable levels. Furthermore, I thought that it would make sense from the development and testing perspective to have levels as a completely separate entity that can be modified as necessary. For example, when a new power-up was introduced, I wanted to add an extra line in a level file and test it out. This was ultimately achieved by creating an XML-based level engine and in this article I will describe the level structure and design process. Check out the video for this article at https://channel9.msdn.com/Series/FallFury/Part-5-Creating-Levels.  For a complete, offline version of this series, you may download a nicely formatted PDF of all the articles. The First Steps When I started working on the level engine concept, I began designing the potential XML file structure for the level and ended up with the following requirements: • Level Type Identifier – As different levels have different backgrounds and sound themes, there should be a way to mark a level type. There are currently four level types: dream, nightmare, space, and magic bean. • The Starting Character Descriptor – When the game starts, the teddy bear has some initial, basic properties, such as maximum health level, horizontal position, and velocity. • A Collection of Obstacles – For each level, obstacles are positioned differently, and it’s important to specify that. For some obstacles it might be desirable to disable the damage infliction component, while for others it might be good to maximize the damage caused by colliding with them. Also, there are multiple textures associated with different obstacle types, so I wanted to specify the obstacles to render regardless of the selected level type. • A Collection of Monsters – Obstacles are not the only component that can damage the bear during gameplay. There are also monsters that can pop up and shoot at the main character. Similar to the bear, monsters represent a living entity and have some specific properties, such as the initial health, damage, starting position, velocity, and type. • Buttons – These are the bonus point boosters in FallFury. The player collects as many of those as possible, and each of them should be individually positioned to form either a trail or a shape. • Power-Ups – With the basic set of abilities, the bear is able to get some bonuses such as a cape that will speed-up his descent or a bubble that will protect him from incoming shells. The first build of the level engine integrated into FallFuryused percentage-based relative values to position elements on the screen. Although this seemed like a good idea at the time, it became problematic because • It required the level to be a fixed size, which restricted element addition and level extension. • It caused problems with obstacles that needed to be scaled and therefore had a non-standard size. • Small modifications were harder to make because minimal adjustments would throw off the relative position. So, I switched to a pixel-based conditioning in which each position is relative to zero. With this in place, levels can be infinitely long (within the context of the machine’s rendering and memory capabilities)and extra elements can be more seamlessly added. Additionally, levels need to be packaged together in individual sets, normally grouped by themes, without restriction. This is achieved with the help of an extra XML file,called core.xml, which keeps track of level tiers, and acts as a container that allows the developer to name and easily enable or disable specific levels . The structure for the core.xml file looks like this: <tiers> <tier name="GO, GO, TEDDY"> <level name="mind travels" file="GoGoTeddy\mind.xml"></level> <level name="falling in" file="Nightmare\full_pilot.xml"></level> <level name="frontlines" file="Nightmare\the_beginning.xml"></level> <level name="the chase" file="Nightmare\chasing_monsters.xml"></level> </tier> <tier name="SECRET GARDEN"> <level name="bean stalking" file="Garden\bean_stalking.xml"/> <level name="thorn apart" file="Garden\thorn_apart.xml"/> </tier> <!--<tier name="Obstacle ***TEST***"> <level name="Nightmare 0" file="test\Obstacle\nightmare\0.xml" /> <level name="Nightmare 1" file="test\Obstacle\nightmare\1.xml" /> <level name="Bean 0" file="test\Obstacle\bean\0.xml" /> <level name="Bean 1" file="test\Obstacle\bean\1.xml" /> <level name="Dream 0" file="test\Obstacle\dream\0.xml" /> <level name="Dream 1" file="test\Obstacle\dream\1.xml" /> </tier>--> <!--<tier name="Death ***TEST***"> <level name="Monster 0" file="test\death\0.xml" /> </tier>--> <!--<tier name="Monster ***TEST***"> <level name="0" file="test\Monsters\0.xml" /> <level name="1" file="test\Monsters\1.xml" /> <level name="2" file="test\Monsters\2.xml" /> <level name="3" file="test\Monsters\3.xml" /> <level name="4" file="test\Monsters\4.xml" /> <level name="5" file="test\Monsters\5.xml" /> <level name="6" file="test\Monsters\6.xml" /> <level name="7" file="test\Monsters\7.xml" /> <level name="8" file="test\Monsters\8.xml" /> <level name="9" file="test\Monsters\9.xml" /> <level name="10" file="test\Monsters\10.xml" /> </tier>--> <!--<tier name="MEDALS *****TEST******"> <level name="gold" file="test\Medals\gold.xml"></level> <level name="silver" file="test\Medals\silver.xml"></level> <level name="bronze" file="test\Medals\bronze.xml"></level> </tier> <tier name="Buttons ***TEST***"> <level name="1" file="test\Buttons\single.xml" /> <level name="Lots" file="test\Buttons\multiple.xml" /> </tier> <tier name="Obstacles ***TEST***"> <level name="Cape" file="test\PowerUps\0.xml" /> </tier>--> </tiers> Tiers that are commented out are ignored and the included levels aren’t on the game list. Also, the paths indicated for each file attribute—for each individual tier—are relative to the game folder itself. There is no limit on the number of subfolders that can be included in the path. The above structure will render this level set: clip_image002 The Level XML Let’s now take a look at the layout of the level descriptor XML file: <?xml version="1.0" encoding="utf-8" ?> <level type="0"> <meta score="0" buttonPrice="10"></meta> <bear maxHealth="100" startPosition="300" velocity="8.0" damage="11" criticalDamage="20" defaultAmmo="100" /> <obstacles> <obstacle type="1" x="119" y="2300" inflictsDamage="true" healthDamage="5" rotation="3.14" scale="1" /> <obstacle type="3" x="534.5" y="3000" inflictsDamage="true" healthDamage="5" rotation="0" scale="1" /> <obstacle type="3" x="534.5" y="3300" inflictsDamage="true" healthDamage="5" rotation="0" scale="1" /> <obstacle type="1" x="119" y="4200" inflictsDamage="true" healthDamage="5" rotation="3.14" scale="1" /> <obstacle type="2" x="546" y="5000" inflictsDamage="true" healthDamage="5" rotation="0" scale="1" /> <obstacle type="1" x="119" y="5800" inflictsDamage="true" healthDamage="5" rotation="3.14" scale="1" /> <obstacle type="2" x="546" y="6600" inflictsDamage="true" healthDamage="5" rotation="0" scale="1" /> </obstacles> <monsters> <monster lifetime="3000" scale=".2" velocityX="2" velocityY="2" type="0" x="460" y="19900" maxHealth="80" bonus="100" lives="0" damage="10" criticalDamage="8" defaultAmmo="50" /> <monster lifetime="3000" scale=".2" velocityX="2" velocityY="2" type="1" x="460" y="25000" maxHealth="80" bonus="100" lives="0" damage="10" criticalDamage="8" defaultAmmo="50" /> <monster lifetime="3000" scale=".2" velocityX="2" velocityY="2" type="2" x="460" y="34500" maxHealth="80" bonus="100" lives="0" damage="10" criticalDamage="8" defaultAmmo="50" /> <monster lifetime="6000" scale=".4" velocityX="2" velocityY="2" type="3" x="460" y="41400" maxHealth="180" bonus="100" lives="0" damage="17" criticalDamage="8" defaultAmmo="50" /> </monsters> <buttons> <button x="300" y="800" /> <button x="360" y="800" /> <button x="300" y="860" /> <button x="360" y="860" /> <button x="300" y="920" /> <button x="360" y="920" /> <button x="300" y="980" /> <button x="360" y="980" /> </buttons> <powerups> <powerup category="1" type="4" x="140" y="9200" effect="3" lifespan="4"></powerup> <powerup category="1" type="3" x="480" y="19800" effect="10" lifespan="6"></powerup> <powerup category="1" type="0" x="480" y="27500" effect="10" lifespan="6"></powerup> <powerup category="1" type="1" x="100" y="34000" effect="10" lifespan="6"></powerup> <powerup category="1" type="0" x="100" y="41200" effect="10" lifespan="6"></powerup> </powerups> </level> The opening level tag carries a type attribute. This is level theme flag. It can be set to one of the three four values: • 0 – The Nightmare Theme • 1 – The Magic Bean Theme • 2 – The Dream Theme • 3 – The Space Theme You can see the design differences in the images below: clip_image004 clip_image006 Nightmare Magic Bean   clip_image008 clip_image010 Dream Space Remember, that obstacles and the level theme itself do not influence much other than the background and soundboard. Once the type is specified, the meta tag brings up the score and buttonPrice attributes. If you for some reason want to create a level including an initial score, you can specify it here. And because buttons are fixed bonus assets that are all created equal, each of them carries a given bonus point weight. The score based on the collected buttons is calculated at the end of the game and relies on the value specified in the meta tag. Obstacles Next comes the obstacle collection, which is represented by the obstacles tag. This tag is required even if there are no obstacles on a given level. Simply use <obstacles /> as necessary. Each child node represents an instance of an obstacle that can be choosen from the following enum: enum class ObstacleType { OT_CLOUD = 0, OT_SPIKE_NIGHTMARE_LARGE = 1, OT_SPIKE_NIGHTMARE_MEDIUM = 2, OT_SPIKE_NIGHTMARE_SMALL = 3, OT_BEAN_A = 4, OT_BEAN_B = 5, OT_BEAN_C = 6, OT_BEAN_D = 7, OT_BEAN_E = 8, OT_SPACE_ROCKET = 9, OT_SPACE_COMET_A = 10, OT_SPACE_COMET_B = 11, OT_SPACE_SATELLITE = 12, OT_SPACE_UFO = 13, OT_SPACE_BALL = 14 }; Here is the complete table showing the appearance of each of them: OT_CLOUD clip_image012    OT_SPIKE_NIGHTMARE_LARGE clip_image014    OT_SPIKE_NIGHTMARE_MEDIUM clip_image016    OT_SPIKE_NIGHTMARE_SMALL clip_image018    OT_BEAN_A clip_image020    OT_BEAN_B clip_image022    OT_BEAN_C clip_image024    OT_BEAN_D clip_image026    OT_BEAN_E clip_image028    OT_SPACE_ROCKET clip_image030    OT_SPACE_COMET_A clip_image032    OT_SPACE_COMET_B clip_image034    OT_SPACE_SATELLITE clip_image036    OT_SPACE_UFO clip_image038    OT_SPACE_BALL clip_image040 No matter how the obstacles are positioned, they will either be located in the visible area or displaced outside the viewport and not displayed. The ultimate position is taken from the obstacle size and is relative to the center of the texture. For example, if an obstacle texture is 400- pixels wide, the X-relative position should be set to 200. If the position differs from the starting one, however, the obstacle texture is cut to include the area that fits in the 768 pixel wide playable zone visible. There are no restrictions regarding the Y position. To help in level creation, some obstacles have pre-defined left and right margins. For example: • OT_BEAN_A: 269.5 (Left), 498.5 (right, with 3.14 rotation) • OT_BEAN_B: 128.5 (left), 638.5 (right, with 3.14 rotation) • OT_BEAN_C: 172 (left), 596 (right, with 3.14 rotation) • OT_BEAN_D: 188.5 (left), 579.5 (right, with 3.14 rotation) • OT_BEAN_E: 206.5 (left), 561.5 (right, with 3.14 rotation) The inflictsDamage attribute determines whether the obstacle harms the main character. If it is set to false, the character will still make the sound of colliding with it but will not lose any health points. The primary use for this attribute is level testing.If it is set to true, the character will loose the amount of health points indicated by the healthDamage attribute. The rotation and scale attributes can be used to flip and resize the texture as needed. Rotation is measured in radians, and the scale is a normalized value in which 1.0 represents 100% of the scale. Monsters As with obstacles, the monsters node should never be omitted from the file and should at least contain a placeholder: <monsters />. Unlike obstacles, however, monsters are dynamic and do not have fixed positions. Moreover, monsters have limited active time during gameplay. The first attribute,lifetime, determines the length of the fall during which the monster will be visible in the viewport. With the y attribute as the Y-based position at which the monster appears, at the y+lifetime position the monster simply flies away if not killed. The scale attribute carries the same purpose as the one for the obstacle—normalized texture size relative to the size of the original image file. As such, the level designer does not have to worry about linking the width and height of the monster when resizing and can instead use a percentage-like value to scale the monster up or down, simultaneously modifying both the width and the height with zero stretching. Nextup are velocityX and velocityY. These two attributes are used to set the motion velocity when the monster is already visible. Instead of being a static shooting entity, the enemy moves on a randomized zig-zag path at the bottom of the screen. The horizontal and vertical displacement—in pixels, per update cycle—is individually set through the values carried by the above-mentioned attributes. If necessary, this functionality can be disabled in the code-behind by assigning a fixed value for the vertical and horizontal movement for all monsters that are being loaded on a given level. The monster type is an integer value that is translated in a value from the following enum (located in MonsterType.h): enum class MonsterType { MT_NIGHTMARE_A = 0, MT_NIGHTMARE_B = 1, MT_NIGHTMARE_C = 2, MT_MAGICBEAN_A = 3, MT_MAGICBEAN_B = 4, MT_MAGICBEAN_C = 5, MT_CANDYLAND_A = 6, MT_CANDYLAND_B = 7, MT_CANDYLAND_C = 8, MT_CANDYLAND_D = 9, MT_CANDYLAND_E = 10 }; Here is a table that shows the texture associated with each identifier: MT_NIGHTMARE_A clip_image042    MT_NIGHTMARE_B clip_image044    MT_NIGHTMARE_C clip_image046    MT_MAGICBEAN_A clip_image048    MT_MAGICBEAN_B clip_image050    MT_MAGICBEAN_C clip_image052    MT_CANDYLAND_A clip_image054    MT_CANDYLAND_B clip_image056    MT_CANDYLAND_C clip_image058    MT_CANDYLAND_D clip_image060    MT_CANDYLAND_E clip_image062    Each monster has three separate textures associated with it. The three textures are cycled inside the update loop for each monster entity when the monster becomes visible, creating the movement effect: clip_image063 Each monster currently shoots only one type of ammo: a red plasma ball. Be aware, however, that there is a preprogrammed condition in which the last monster in the XML file collection is automatically considered the final boss. This means the scale, maxHealth and lifetime properties must be manually adjusted to reflect the effect. Without doing so, the last monster will, regardless of the XML setting, switch in-game to a triple fireball shot that inflicts three times the damage indicated by the damage attribute: clip_image065 Each monster can have limited ammo as set by the defaultAmmo attribute. In the case that the ammo is exhausted before the monster expires, the monster will continue its motion at the bottom of the screen without inflicting direct damage to the main character. Buttons These are the least complex entities and only carry an X and a Y position. Given those coordinates, relative to the left margin of the visible area, a button texture is rendered: clip_image067 Once picked-up, the button counter is increased by one and the meta-score incremented by the value set in the meta tag at the beginning of the level XML as long as the feature is activated in the code-behind. Power-ups To make the game more fun, there are bonus elements that can be picked up by the bear in order to enhance its performance or protection. These elements are declared in the <powerups/> collection. First and foremost, it is important to declare whether the power-up is positive or negative. In the current version of FallFury, only positive power-ups are included. Nonetheless, the harness for negative ones is already integrated in the parser. Therefore, the category attribute should be set to 1 if the power-up has a positive effect and 0 for a negative effect. This value will only have an effect over the sound played when the bonus is collected. The power-up type can be one of the following (enum located in PoweupType.h): enum class PowerupType { HEALTH = 0, HELMET = 1, PARACHUTE = 2, BUBBLE = 3, CAPE = 4, AXE = 5, BOOMERANG = 6, HAMMER = 7, KNIFE = 8, PLASMA_BALL = 9, CIRCLE = 10 };   The table below shows the power-up texture appearance. Behaviors are already defined in the game and influenced by only the effect and lifespan (seconds) attributes: HEALTH Restores the character health, incremented by the value in effect. The lifespan attribute is ignored. clip_image069 HELMET Adds a helmet to the bear, setting the maximum health to the effect value. Active for the duration of lifespan. clip_image071 PARACHUTE Slows down the fall of the bear, setting the descent velocity to the effect value. Active for the duration of lifespan. clip_image073 BUBBLE Wraps the character in a protective bubble, setting the maximum health to the value of the effect attribute. Active for the duration of lifespan. clip_image075 CAPE Accelerates the descent by multiplying the velocity by the value of effect. Active for the duration of lifespan. clip_image077 AXE Sets the current character weapon to an axe. The damage is determined by the effect attribute and lifespan is ignored. clip_image079 BOOMERANG Sets the current character weapon to a boomerang. The damage is determined by the effect attribute and lifespan is ignored. clip_image081 HAMMER Sets the current character weapon to a hammer. The damage is determined by the effect attribute and lifespan is ignored. clip_image083 KNIFE Sets the current character weapon to a knife. The damage is determined by the effect attribute and lifespan is ignored. clip_image085 PLASMA_BALL Sets the current character weapon to a plasma ball. The damage is determined by the effect attribute and lifespan is ignored. clip_image087 CIRCLE is a helper power-up that has no effect on the bear and is instead used as an additional texture overlay along with any other power-up in order to create a pulsating circle effect. Conclusion FallFury ships with a dozen of sample levels that showcase all of the elements described in the article. At the moment, a level editor is in the works, but it isn’t too complicated to build XML files manually. To do so, you need to consider the pixel-based locations and ensure that they’re all in the visible area—the game engine will automatically handle all other displacements and adjustments. ]]> https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-5-Creating-Levels Creating LevelsOne of the goals set when developing FallFury was making the game extensible in regards to playable levels. Furthermore, I thought that it would make sense from the development and testing perspective to have levels as a completely separate entity that can be modified as necessary. For example, when a new power-up was introduced, I wanted to add an extra line in a level file and test it out. This was ultimately achieved by creating an XML-based level engine and in this article I will describe the level structure and design process. Check out the video for this article at https://channel9.msdn.com/Series/FallFury/Part-5-Creating-Levels. For a complete, offline version of this series, you may download a nicely formatted PDF of all the articles. The First StepsWhen I started working on the level engine concept, I began designing the potential XML file structure for the level and ended up with the following requirements: Level Type Identifier – As different levels have different backgrounds and sound themes, there should be a way to mark a level type. There are currently four level types: dream, nightmare, space, and magic bean. The Starting Character Descriptor – When the game starts, the teddy bear has some initial, basic properties, such as maximum health level, horizontal position, and velocity. A Collection of Obstacles – For each level, obstacles are positioned differently, and it’s important to specify that. For some obstacles it might be desirable to disable the damage infliction component, while for others it might be good to maximize the damage caused by colliding with them. Also, there are multiple textures associated with different obstacle types, so I wanted to specify the obstacles to render regardless of the selected level type. A Collection of Monsters – Obstacles are not the only component that can damage the bear during gameplay. There are also monsters that can pop up and shoot at the main character. Similar to the bear, monsters repre https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-5-Creating-Levels Wed, 23 Jan 2013 23:57:11 GMT https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-5-Creating-Levels Brian Peek, Clint Rutkas, Dan Fernandez, Den Delimarsky, Rick Barraza Brian Peek, Clint Rutkas, Dan Fernandez, Den Delimarsky, Rick Barraza 0 https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-5-Creating-Levels/RSS C# C++ DirectX Windows Store App Fall Fury: Part 4 - XAML Interop As mentioned earlier in the series, FallFury does not solely rely on DirectX to display content to the user. As a Windows Store game, FallFury leverages the new Direct2D (XAML) project template, available in Visual Studio 2012.  Check out the video for this article at https://channel9.msdn.com/Series/FallFury/Part-4-XAML-Interop.  For a complete, offline version of this series, you may download a nicely formatted PDF of all the articles. The Concept of a Swap Chain Before I go into detail about the DirectX and XAML interop in FallFury, I want to cover one important aspect of DirectX development that you need to familiarize yourself with: the swap chain. When your graphics adapter draws on the visual surface, you, as the user, see only minor potential redraws. Internally, however, the device switches buffers that reflect the displayed content, with each buffer representing a frame that has to be drawn. You can deduce from this that any swap chain has at least two buffers that it can switch between. For example, if I want to display my character as being displaced by a specific amount of pixels, the buffer will at the outset present to me the character in its initial position, while the second buffer will be constructed in the background with the proper position adjustments. The first frame, made from the content from the first buffer, will be discarded, and then the second frame will be displayed, and so on. This process occurs at a very high speed that depends on the processing capabilities of the graphics adapter, so the user does not notice the swapping itself. The most common swap chain is composed of two buffers—the screenbuffer and the secondary framebuffer. SwapChainBackgroundPanel DirectX interoperability with XAML simplifies a lot of routine tasks that would otherwise be handled with manual rendering procedures, such as a menu system or a simple game HUD. That being said, the way the XAML workflow is organized in a Direct2D project is quite different compared to a standard XAML Windows Store or Windows Phone application. The core difference is that there is no navigational system per-se and the fundamental entity in a Direct2D (XAML) project that manages the XAML content is a SwapChainBackgroundPanel control. This control allows the developer to overlay XAML elements on top of the DirectX renders. It replaces the normal page-based layout with one in which it is sole container for every XAML control that has to be used in the application. This necessitates that you will have to organize the secondary elements in such a way that the correct set is displayed for the current application state. For example, if the user is in the main menu, menu options as well as the game logo should be shown. When the user switches to the game mode, the HUD should appear and the menu should become hidden. Although both the menu and the HUD are a part of the same SwapChainBackgroundPanel, I will have to manually manage state and visibility changes. Using the SwapChainBackgroundPanel also means that you will have to enforce specific graphic configuration rules in your application. One of them applies to setting up the swap chain. When you set up the scaling, it must be set to DXGI_SCALING_STRETCH: DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0}; swapChainDesc.Width = static_cast<UINT>(m_renderTargetSize.Width); swapChainDesc.Height = static_cast<UINT>(m_renderTargetSize.Height); swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; swapChainDesc.Stereo = false; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.BufferCount = 2; swapChainDesc.Scaling = DXGI_SCALING_STRETCH; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; swapChainDesc.Flags = 0;   The swap chain itself should be configured for composition, mixing the native DirectX buffer with the overlaid XAML. This is done by calling CreateSwapChainForComposition: ThrowIfFailed( dxgiFactory->CreateSwapChainForComposition( m_d3dDevice.Get(), &swapChainDesc, nullptr, &m_swapChain ) ); ComPtr<ISwapChainBackgroundPanelNative> panelNative; ThrowIfFailed( reinterpret_cast<IUnknown*>(m_panel)->QueryInterface(IID_PPV_ARGS(&panelNative)) ); ThrowIfFailed( panelNative->SetSwapChain(m_swapChain.Get()) ); There really isn’t much additional configuration work beyond this point. Remember, that the XAML content will always be overlaid on top of the DirectX content; therefore, plan the game components accordingly. The XAML Menu System The menu is at the core of the FallFury experience. When designing it, I was inspired by how Dance Central built the user interaction mechanism, and I tried to implement a similar approach in which the user would have to slide the button to the right instead of simply tapping on it: clip_image002 Each menu item is built around a custom MenuItem control (MenuItem.xaml): <UserControl x:Class="Coding4Fun.FallFury.MenuItem" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:Coding4Fun.FallFury" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Name="menuItem" Margin="10, 0, 0, 10"> <Grid Height="65" ManipulationMode="TranslateX" ManipulationCompleted="Grid_ManipulationCompleted" ManipulationDelta="Grid_ManipulationDelta" x:Name="ControlContainer" PointerPressed="Grid_PointerPressed" PointerReleased="Grid_PointerReleased"> <Grid.Resources> <Storyboard x:Name="ArrowAnimator"> <DoubleAnimation Storyboard.TargetName="ImageTranslateTransform" Storyboard.TargetProperty="X" From="0" To="20" Duration="0:0:0.4" RepeatBehavior="Forever" AutoReverse="True"> </DoubleAnimation> </Storyboard> </Grid.Resources> <Grid.RowDefinitions> <RowDefinition Height="10" /> <RowDefinition /> <RowDefinition /> <RowDefinition Height="10" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="10" /> <ColumnDefinition /> </Grid.ColumnDefinitions> <StackPanel Orientation="Horizontal" Grid.RowSpan="4" Grid.ColumnSpan="4"> <!-- width is sent in code behind, have to get this dynamic ... --> <Grid Width="350" x:Name="coverRectangle"> <Rectangle Fill="#303030" /> <Rectangle Fill="Red" x:Name="coverActiveRectangle" /> </Grid> <Image x:Name="MenuImage" Source="ms-appx:///MenuItems/single_arrow.png" Margin="10,0,0,0" Stretch="Uniform"> <Image.RenderTransform> <TranslateTransform x:Name="ImageTranslateTransform"></TranslateTransform> </Image.RenderTransform> </Image> </StackPanel> <!----> <TextBlock Text="{Binding ElementName=menuItem, RelativeSource={RelativeSource Self}, Path=Label}" Grid.RowSpan="4" Grid.ColumnSpan="4" Style="{StaticResource MenuItemText}"> </TextBlock> <MediaElement x:Name="coreMenuMedia" Source="ms-appx:///Assets/Sounds/MenuTap.wav" AutoPlay="False"></MediaElement> <MediaElement x:Name="slideMenuMedia" Source="ms-appx:///Assets/Sounds/MenuSlide.wav" AutoPlay="False"></MediaElement> </Grid> </UserControl> There is a core storyboard that is used to perform an image bounce. Initial tests showed that that most users tend to follow the standard “click-and-go” pattern and even though the implemented button was a slider, they tried to click it at least once, expecting the game to take them to the next screen. To avoid this, I introduced a visual arrow indicator that bounces left and right to indicate the direction of the necessary slide. When the sliding occurs, the overlay grid width is being adjusted relative to the manipulation. At the same time, the button changes from passive state (dark background): clip_image003 to active state (red background): clip_image004 Internally, the double-arrow image replaces the single-arrow one and is translated across the X-axis to create a bouncing effect: void MenuItem::Grid_PointerPressed(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ e) { BitmapImage^ image = ref new BitmapImage(ref new Uri("ms-appx:///MenuItems/double_arrow.png")); MenuImage->Source = image; coverActiveRectangle->Visibility = Windows::UI::Xaml::Visibility::Visible; ((Storyboard^)ControlContainer->Resources->Lookup("ArrowAnimator"))->Begin(); coreMenuMedia->Play(); } As the user drags the finger on the button, the red overlay size should be adjusted accordingly. The size adjustment can be easily tracked in the ManipulationDelta event handler for the focused grid: void MenuItem::Grid_ManipulationDelta(Platform::Object^ sender, Windows::UI::Xaml::Input::ManipulationDeltaRoutedEventArgs^ e) { double diff = e->Cumulative.Translation.X; if (diff > maxDeltaSize) { diff = maxDeltaSize; } else if (diff < 0) { diff = 0; } coverRectangle->Width = initialBarWidth + diff; } When the user action on the button is completed, the ManipulationCompleted event handler is triggered on the same overlay grid. If the relative drag hits the critical threshold, the action linked to the button should be invoked: void MenuItem::Grid_ManipulationCompleted(Platform::Object^ sender, Windows::UI::Xaml::Input::ManipulationCompletedRoutedEventArgs^ e) { float diff = e->Cumulative.Translation.X; if (diff > maxDeltaSize - 50) // slight buffer { slideMenuMedia->Play(); OnButtonSelected(this, Label); } ResetElements(); } There are also local sound effects that are played when the slider-button is tapped and moved to the end. Both are handled by separate MediaElement controls that avoid an internal sound file switch, calling instead the Play method as necessary. The OnButtonSelected event handler can be dynamically hooked in the application backend. Each button also has a visible content area that can display a text label. It can be set through a DependencyProperty: DependencyProperty^ MenuItem::_LabelProperty = DependencyProperty::Register("Label", Platform::String::typeid, MenuItem::typeid, nullptr); In its current configuration, the menu label can be also set in XAML: <local:MenuItem x:Name="btnNewGame" Label="new game"> <local:MenuItem.RenderTransform> <TranslateTransform></TranslateTransform> </local:MenuItem.RenderTransform> </local:MenuItem> When the button loses the focus, the state resets to the passive one, stopping the animation and resetting the arrow image to the single one: void MenuItem::ResetElements() { BitmapImage^ image = ref new BitmapImage(ref new Uri("ms-appx:///MenuItems/single_arrow.png")); MenuImage->Source = image; ((Storyboard^)ControlContainer->Resources->Lookup("ArrowAnimator"))->Stop(); coverRectangle->Width = initialBarWidth; coverActiveRectangle->Visibility = Windows::UI::Xaml::Visibility::Collapsed; } That’s about as complex as the menu item control will get. The menu container itself can be any Grid or StackPanel control. The way the menu items are used across the game states, there is no need to have a separate unified container. The Main XAML Container & State Changes Going back to DirectXPage.xaml, there are several parts of the XAML layout that should be highlighted. First and foremost, the game curtains—the static parts of the screen that are being displayed instead of blacking out parts of the viewport that are not being used when the game runs in landscape mode. Because the game includes a rectangular frame instead of stretching the entire playable area to the size of the screen, there is an unknown amount of unallocated visual space on both the right and left sides of the frame itself: <Grid HorizontalAlignment="Left" x:Name="containerA"> <Rectangle Fill="#09bbe3" /> <Rectangle Width="10" HorizontalAlignment="Left"> <Rectangle.Fill> <LinearGradientBrush StartPoint="0,0" EndPoint="1,0"> <GradientStop Color="#a000" Offset="0.0"></GradientStop> <GradientStop Color="#0000" Offset="1.0"></GradientStop> </LinearGradientBrush> </Rectangle.Fill> </Rectangle> </Grid> <Grid HorizontalAlignment="Right" x:Name="containerB"> <Rectangle Fill="#09bbe3" /> <Rectangle Width="10" HorizontalAlignment="Right"> <Rectangle.Fill> <LinearGradientBrush StartPoint="1,0" EndPoint="0,0"> <GradientStop Color="#a000" Offset="0.0"></GradientStop> <GradientStop Color="#0000" Offset="1.0"></GradientStop> </LinearGradientBrush> </Rectangle.Fill> </Rectangle> </Grid> Although these two grids have set alignments, the actual location on the screen will be set in code-behind because the size will also be re-calculated. Also, I need to make sure that the application is in the full display mode—if it is snapped, there is no need to display the curtains because the visible area will be reduced to an overlay grid. The curtain resize and visibility are determined in the UpdateWindowSize method: void DirectXPage::UpdateWindowSize() { bool visibility = true; if (ApplicationView::Value == ApplicationViewState::Snapped) visibility = false; float margin = (m_renderer->m_renderTargetSize.Width - 768.0f) / 2.0f; if (margin < 2.0) visibility = false; if (visibility) { containerA->Width = margin; containerA->HorizontalAlignment = Windows::UI::Xaml::HorizontalAlignment::Right; containerB->Width = margin; containerB->HorizontalAlignment = Windows::UI::Xaml::HorizontalAlignment::Left; containerA->Visibility = Windows::UI::Xaml::Visibility::Visible; containerB->Visibility = Windows::UI::Xaml::Visibility::Visible; } else { containerA->Visibility = Windows::UI::Xaml::Visibility::Collapsed; containerB->Visibility = Windows::UI::Xaml::Visibility::Collapsed; } } The snippet above ensures that the curtains will only be displayed when there is extra, unused space in addition to the 768 pixels taken by the playable area. Let’s take a look at state-specific content that is being displayed whenever the game switches states. Because of the nature of DirectX interaction, there is no way for me to hook to specific event handlers from the native loop. Therefore, I need to constantly check that the content displayed is associated with the current state. This can be done with the help of the SwitchGameState method: void DirectXPage::SwitchGameState() { switch (m_renderer->CurrentGameState) { case GameState::GS_FULL_WIN: { grdCompleteWin->Visibility = Windows::UI::Xaml::Visibility::Visible; break; } case GameState::GS_PLAYING: { Hud->Visibility = Windows::UI::Xaml::Visibility::Visible; break; } case GameState::GS_MAIN_MENU: { stkMainMenu->Visibility = Windows::UI::Xaml::Visibility::Visible; break; } case GameState::GS_GAME_OVER: { UpdateResults(); ResultPanel->Visibility = Windows::UI::Xaml::Visibility::Visible; grdGameOver->Visibility = Windows::UI::Xaml::Visibility::Visible; break; } case GameState::GS_SUBMIT_SCORE: { grdSubmitScore->Visibility = Windows::UI::Xaml::Visibility::Visible; txtSubmitScoreView->Text = StaticDataHelper::Score.ToString(); break; } case GameState::GS_TOP_SCORES: { grdTopScores->Visibility = Windows::UI::Xaml::Visibility::Visible; break; } case GameState::GS_WIN: { UpdateResults(); grdWinner->Visibility = Windows::UI::Xaml::Visibility::Visible; ResultPanel->Visibility = Windows::UI::Xaml::Visibility::Visible; break; } case GameState::GS_ABOUT_SCREEN: { grdAbout->Visibility = Windows::UI::Xaml::Visibility::Visible; break; } case GameState::GS_LEVEL_SELECT_SINGLE: { animationBeginTime = 0; stkLevelSelector->Visibility = Windows::UI::Xaml::Visibility::Visible; break; } case GameState::GS_HOW_TO: { grdHowTo->Visibility = Windows::UI::Xaml::Visibility::Visible; Storyboard^ howToInitialBoard = (Storyboard^)grdMain->Resources->Lookup("StoryboardChainA"); howToInitialBoard->Begin(); break; } default: break; } Storyboard^ loc = (Storyboard^)grdMain->Resources->Lookup("FadingOut"); loc->Begin(); } One thing you’ve probably noticed about the snippet above is the fact that there is no indicator showing that controls are being hidden when the state changes. Just calling SwitchGameState in the Update loop would cause multiple controls to be displayed at once. However, there is also the HideEverything method that goes through the visual tree and sets the Visibility to Collapsed for everything: void DirectXPage::HideEverything() { for (uint i = 0; i < grdMain->Children->Size; i++) { grdMain->Children->GetAt(i)->Visibility = Windows::UI::Xaml::Visibility::Collapsed; } }   HUD Interaction The Heads-Up Display (HUD) is used to alert the player about the current state of the game and the game character. In FallFury, it is used to display three indicators: how many buttons the character collected, how much time it took the character to get to the current level part, and current character health. It is also the container for the Pause button. Here is the visual representation: clip_image006 Here is the underlying XAML: <Grid x:Name="Hud" VerticalAlignment="Top" Visibility="Collapsed"> <Grid.RowDefinitions> <RowDefinition Height="80" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> <ColumnDefinition /> <ColumnDefinition Width="80" /> </Grid.ColumnDefinitions> <Rectangle Fill="Black" Grid.ColumnSpan="4" /> <Button Grid.Column="0" x:Name="btnPause" Click="btnPause_Click" Style="{StaticResource PauseButton}"> <Image Source="ms-appx:///Assets/HUD/pauseButton.png" Stretch="None" / </Button> <StackPanel Grid.Column="1" Orientation="Horizontal"> <Image Source="ms-appx:///Assets/HUD/buttonHud.png" Stretch="None" /> <TextBlock x:Name="txtButtons" Text="0" Style="{StaticResource hudResult}"/> </StackPanel> <StackPanel Grid.Column="2" Orientation="Horizontal"> <Image Source="ms-appx:///Assets/HUD/clockHud.png" Stretch="None" /> <TextBlock x:Name="txtTimer" Text="00:00" Style="{StaticResource hudResult}"/> </StackPanel> <Image Grid.Column="3" Source="ms-appx:///Assets/HUD/heartHud.png" Stretch="None" /> <Grid Grid.Column="3" Grid.Row="1"> <Rectangle Fill="Black" Opacity=".8"/> <controls:HealthBar x:Name="healthBar"></controls:HealthBar> </Grid> </Grid> As I mentioned before, the DirectX layer cannot directly interact with the XAML layer. Therefore, there needs to be an intermediary binding class. As the game progress changes, the UpdateHUD method is called, taking a reference to the current DirectX screen and reading the game data from the character and the StaticDataHelper class, which is the container for the time elapsed: void DirectXPage::UpdateHud(GamePlayScreen^ playScreen) { healthBar->Update(playScreen->GameBear->CurrentHealth, playScreen->GameBear->MaxHealth); txtButtons->Text = StaticDataHelper::ButtonsCollected.ToString(); // Find a better built-in string formatting code if (m_renderer->CurrentGameState == GameState::GS_PLAYING && !(StaticDataHelper::IsPaused) && playScreen->IsLevelLoaded) { StaticDataHelper::SecondsTotal += m_timer->Delta; txtTimer->Text = StaticDataHelper::GetTimeString((int)StaticDataHelper::SecondsTotal); } } As seen above, part of the HUD is taken by a health indicator control—HealthBar. It is a simple composite element made out of two overlaying rectangles, one of which is resized as the bear health changes: <UserControl x:Class="Coding4Fun.FallFury.Controls.HealthBar" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:FallFury" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignHeight="410" d:DesignWidth="20" Height="410" Width="20"> <Grid> <StackPanel VerticalAlignment="Top" Margin="0, 5, 0,20"> <Rectangle Height="400" Style="{StaticResource HealthRectangle}" /> </StackPanel> <StackPanel VerticalAlignment="Top" Margin="0, 5, 0, 10"> <Rectangle x:Name="OverlayStacker" Height="0" Style="{StaticResource HealthOverlayRectangle}" /> </StackPanel> </Grid> </UserControl> Being of a fixed size, it is fairly easy to calculate the health-to-damage ratio and display that as the size of the overlaid rectangle: DependencyProperty^ HealthBar::_MaxHealthProperty = DependencyProperty::Register("MaxHealth", double::typeid, HealthBar::typeid, nullptr); DependencyProperty^ HealthBar::_CurrentHealthProperty = DependencyProperty::Register("CurrentHealth", double::typeid, HealthBar::typeid, nullptr); void HealthBar::Update(double currentHealth, double maxHealth) { CurrentHealth = currentHealth; MaxHealth = maxHealth; if (CurrentHealth >= 0) { OverlayStacker->Height = 400.0 - ((400.0 * CurrentHealth) / MaxHealth); } } Conclusion Using XAML as a part of a DirectX application does not require the developer to do a massive overhaul of the infrastructure. That said, be mindful when deciding whether to use a hybrid XAML application, as it is much easier to integrate a SwapChainBackgroundPanel with the underlying DirectX configuration from the ground up instead of trying to do so when the DirectX component is completed. ]]> https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-4-XAML-Interop As mentioned earlier in the series, FallFury does not solely rely on DirectX to display content to the user. As a Windows Store game, FallFury leverages the new Direct2D (XAML) project template, available in Visual Studio 2012. Check out the video for this article at https://channel9.msdn.com/Series/FallFury/Part-4-XAML-Interop. For a complete, offline version of this series, you may download a nicely formatted PDF of all the articles. The Concept of a Swap ChainBefore I go into detail about the DirectX and XAML interop in FallFury, I want to cover one important aspect of DirectX development that you need to familiarize yourself with: the swap chain. When your graphics adapter draws on the visual surface, you, as the user, see only minor potential redraws. Internally, however, the device switches buffers that reflect the displayed content, with each buffer representing a frame that has to be drawn. You can deduce from this that any swap chain has at least two buffers that it can switch between. For example, if I want to display my character as being displaced by a specific amount of pixels, the buffer will at the outset present to me the character in its initial position, while the second buffer will be constructed in the background with the proper position adjustments. The first frame, made from the content from the first buffer, will be discarded, and then the second frame will be displayed, and so on. This process occurs at a very high speed that depends on the processing capabilities of the graphics adapter, so the user does not notice the swapping itself. The most common swap chain is composed of two buffers—the screenbuffer and the secondary framebuffer. SwapChainBackgroundPanelDirectX interoperability with XAML simplifies a lot of routine tasks that would otherwise be handled with manual rendering procedures, such as a menu system or a simple game HUD. That being said, the way the XAML workflow is organized in a Direct2D project is quite different compared https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-4-XAML-Interop Wed, 23 Jan 2013 23:57:07 GMT https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-4-XAML-Interop Brian Peek, Clint Rutkas, Dan Fernandez, Den Delimarsky, Rick Barraza Brian Peek, Clint Rutkas, Dan Fernandez, Den Delimarsky, Rick Barraza 0 https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-4-XAML-Interop/RSS C# C++ DirectX Windows Store App Fall Fury: Part 3 - Basic Rendering and Movement Continuing the FallFury series, in this article I talk about basic game element rendering and character movement. As you already know, the FallFury user experience stack is split across two layers—native DirectX and XAML. Here, I will only be talking about the native DirectX component.  Check out the video for this article at https://channel9.msdn.com/Series/FallFury/Part-3-Basic-Rendering-and-Movement  For a complete, offline version of this series, you may download a nicely formatted PDF of all the articles. The Background Each game screen in FallFury has a moving background that creates the illusion of a fall. The way the screen is designed, it simulates vertical parallax scrolling, as the background moves faster than the overlaid objects. There is a simple way to make background movement possible without actually having to replicate parts of the texture and render them all over again. Take a look at this image, showcasing the process: image First of all, two textures are loaded that, connected at the bottom, create the illusion of a single texture. In the beginning, texture A takes the entire screen and texture B is positioned directly underneath it, with a non-existing gap between them. To initiate the scrolling, texture A is being displaced vertically by an arbitrary number of pixels, and texture B follows it at the same pace. As texture B reaches the zero point (top of the viewport), texture A is no longer visible, therefore it is displaced vertically to be below texture B. This cycle can be repeated as many times as necessary during gameplay as well as while the user is in the menu. Let’s take a look at the code that makes it possible, starting with the main menu screen: image First of all, you need to be aware that every game screen is automatically inheriting the properties and capabilities of base class GameScreenBase. This is the class the offers the foundation both for basic texture loading and movement: protected private: // Core background textures Microsoft::WRL::ComPtr<ID3D11Texture2D> m_backgroundBlockA; Microsoft::WRL::ComPtr<ID3D11Texture2D> m_backgroundBlockB; void MoveBackground(float velocity); It also offers the core texture containers for the overlaid elements that are present in most screens, such as clouds: // Overlayed clouds Microsoft::WRL::ComPtr<ID3D11Texture2D> m_overlayA; Microsoft::WRL::ComPtr<ID3D11Texture2D> m_overlayB; The overlay movement is inherently dependent on the base background displacement and can be adjusted relative to the initial velocity. Let’s take a look at GameScreenBase.cpp, specifically at MoveBackground: void GameScreenBase::MoveBackground(float velocity) { if (m_backgroundPositionA <= -BACKGROUND_MIDPOINT) m_backgroundPositionA = m_backgroundPositionB + (BACKGROUND_MIDPOINT * 2); if (m_backgroundPositionB <= -BACKGROUND_MIDPOINT) m_backgroundPositionB = m_backgroundPositionA + (BACKGROUND_MIDPOINT * 2); m_backgroundPositionA -= velocity; m_backgroundPositionB -= velocity; } The BACKGROUND_MIDPOINT value is relative to the height of the background texture. As we are working with a variable screen size, given that tablets and desktops do not have the same resolution, the movement has to be adjusted accordingly. One way, however, to ensure the proper texture positioning would be to place it in relation to its previous instance. Hence, this snippet in UpdateWindowSize: BACKGROUND_MIDPOINT = 1366.0f / 2.0f; m_backgroundPositionA = BACKGROUND_MIDPOINT; m_backgroundPositionB = m_backgroundPositionA * 3; Because overlays are not necessarily a part of every screen, I am not including the MoveOverlay method in the base class. Let’s now take a look at MenuScreen.cpp. Take a look at the Load method and you will see several lines that prepare the background and overlays: m_loader = ref new BasicLoader(Manager->m_d3dDevice.Get(), Manager->m_wicFactory.Get()); m_loader->LoadTexture("Assets\\Backgrounds\\generic_blue_a.png", &m_backgroundBlockA, nullptr); m_loader->LoadTexture("Assets\\Backgrounds\\generic_blue_b.png", &m_backgroundBlockB, nullptr); m_loader->LoadTexture("Assets\\Backgrounds\\cloud_overlay_a.png", &m_overlayA, nullptr); m_loader->LoadTexture("Assets\\Backgrounds\\cloud_overlay_b.png", &m_overlayB, nullptr); CurrentSpriteBatch->AddTexture(m_backgroundBlockA.Get()); CurrentSpriteBatch->AddTexture(m_backgroundBlockB.Get()); CurrentSpriteBatch->AddTexture(m_overlayA.Get()); CurrentSpriteBatch->AddTexture(m_overlayB.Get()); The BasicLoader class was imported from the Direct3D sprite sample. A call to LoadTexture will read the data from a DDS or PNG file and output the data in an ID3D11Texture2D object. Once loaded, the texture is added to the SpriteBatch instance associated with the screen, also declared as a part of GameScreenBase. Depending on the screen, this procedure might have to be done for multiple textures, as you will see later in this article. Each page also has two timed loops—RenderScreen and Update. RenderScreen is responsible for taking everything from the SpriteBatch instance and showing it to the user. If you’ve used the XNA SpriteBatch before, you are aware that you need to start the drawing cycle by calling Begin and end it by calling End. The same applies here: CurrentSpriteBatch->Begin(); CurrentSpriteBatch->Draw( m_backgroundBlockA.Get(), float2(Manager->m_windowBounds.Width / 2, m_backgroundPositionA), PositionUnits::DIPs, m_screenSize, SizeUnits::Pixels); CurrentSpriteBatch->Draw( m_backgroundBlockB.Get(), float2(Manager->m_windowBounds.Width / 2 ,m_backgroundPositionB), PositionUnits::DIPs, m_screenSize, SizeUnits::Pixels); if (m_showBear->IsLoaded) m_showBear->Render(); if (m_showMonster->IsLoaded) m_showMonster->Render(); CurrentSpriteBatch->Draw( m_overlayA.Get(), float2(Manager->m_windowBounds.Width/2, m_backgroundPositionA), PositionUnits::DIPs, m_screenSize, SizeUnits::Pixels); CurrentSpriteBatch->Draw( m_overlayB.Get(), float2(Manager->m_windowBounds.Width / 2 ,m_backgroundPositionB), PositionUnits::DIPs, m_screenSize, SizeUnits::Pixels); CurrentSpriteBatch->End(); The current overloaded Draw call gets the following items: • The texture object • The position where the object has to be drawn on the screen • The way the object is positioned (can also be a normalized value or a pixel value) • The size of the texture (stretching may occur) • The type of the size value (in this case, I am using pixels, but can also be normalized) The order in which the Draw calls are arranged determines the order of objects drawn on the screen. The calls on top will place texture objects at the bottom of the rendering stack, and the calls at the end will place the objects at the top of the stack. The Gameplay Screen Background & Overlays Let’s move on to the arguably most critical screen in the project, GamePlayScreen.cpp. There are a few nuances that differentiate it from any other screen—in particular, the background loading routine. For every game, there is a different level type that is being used. With each level type, there is a different combination of a background and the overlay. Currently, there are four supported level types: • Space • Nightmare • Magic Bean • Dream When the proper level is detected and the metadata is loaded from the associated XML file (more about this process later on in the series), the level textures are loaded into memory: switch (m_currentLevelType) { case LevelType::SPACE: { m_loader->LoadTexture("Assets\\Backgrounds\\generic_dark_blue_a.png", &m_backgroundBlockA, nullptr); m_loader->LoadTexture("Assets\\Backgrounds\\generic_dark_blue_b.png", &m_backgroundBlockB, nullptr); m_loader->LoadTexture("Assets\\Backgrounds\\star_overlay_a.png", &m_overlayA, nullptr); m_loader->LoadTexture("Assets\\Backgrounds\\star_overlay_b.png", &m_overlayB, nullptr); m_loader->LoadTexture("Assets\\Backgrounds\\galaxy_overlay_a.png", &m_overlayGalaxyA, nullptr); m_loader->LoadTexture("Assets\\Backgrounds\\galaxy_overlay_b.png", &m_overlayGalaxyB, nullptr); CurrentSpriteBatch->AddTexture(m_overlayGalaxyA.Get()); CurrentSpriteBatch->AddTexture(m_overlayGalaxyB.Get()); break; } case LevelType::NIGHTMARE: { m_loader->LoadTexture("Assets\\Backgrounds\\generic_red_a.png", &m_backgroundBlockA, nullptr); m_loader->LoadTexture("Assets\\Backgrounds\\generic_red_b.png", &m_backgroundBlockB, nullptr); m_loader->LoadTexture("Assets\\Backgrounds\\cloud_overlay_a.png", &m_overlayA, nullptr); m_loader->LoadTexture("Assets\\Backgrounds\\cloud_overlay_b.png", &m_overlayB, nullptr); break; } case LevelType::MAGIC_BEANS: { m_loader->LoadTexture("Assets\\Backgrounds\\generic_blue_a.png", &m_backgroundBlockA, nullptr); m_loader->LoadTexture("Assets\\Backgrounds\\generic_blue_b.png", &m_backgroundBlockB, nullptr); m_loader->LoadTexture("Assets\\Backgrounds\\cloud_overlay_a.png", &m_overlayA, nullptr); m_loader->LoadTexture("Assets\\Backgrounds\\cloud_overlay_b.png", &m_overlayB, nullptr); break; } case LevelType::DREAM: { m_loader->LoadTexture("DDS\\Levels\\Dream\\TEST_backgroundDream_01.dds", &m_backgroundBlockA, nullptr); m_loader->LoadTexture("DDS\\Levels\\Dream\\TEST_backgroundDream_02.dds", &m_backgroundBlockB, nullptr); m_loader->LoadTexture("Assets\\Backgrounds\\cloud_overlay_a.png", &m_overlayA, nullptr); m_loader->LoadTexture("Assets\\Backgrounds\\cloud_overlay_b.png", &m_overlayB, nullptr); break; } } This way, no unnecessary textures are loaded. A screen-based level flag allows me to control the incoming assets. At this point, the level environment does not change dynamically, so it is safe to assume that the textures should be loaded on a per-level basis. The RenderScreen method is called in the same manner as in the menu screen, with the moving background and overlays located at the bottom of the rendering stack: CurrentSpriteBatch->Draw( m_backgroundBlockA.Get(), float2(Manager->m_windowBounds.Width / 2, m_backgroundPositionA), PositionUnits::DIPs, m_screenSize, SizeUnits::Pixels); CurrentSpriteBatch->Draw( m_backgroundBlockB.Get(), float2(Manager->m_windowBounds.Width / 2, m_backgroundPositionB), PositionUnits::DIPs, m_screenSize, SizeUnits::Pixels); CurrentSpriteBatch->Draw( m_overlayA.Get(), float2(Manager->m_windowBounds.Width / 2, m_overlayPositionA), PositionUnits::DIPs, float2(768.0f, 1366.0f), SizeUnits::Pixels); CurrentSpriteBatch->Draw( m_overlayB.Get(), float2(Manager->m_windowBounds.Width / 2, m_overlayPositionB), PositionUnits::DIPs, float2(768.0f, 1366.0f), SizeUnits::Pixels); Character Movement As you are now aware of the basic screen structure and how the basic rendering process is built, let’s take a look at how the main game character moves on the screen. Falling down, the teddy bear also needs to move left and right to ensure that he is able to pick up power-ups and buttons as well as avoid obstacles and enemy ammo. There are several important considerations here. The most important one is to not assume that the user will have a specific input device. Potential movement controllers include a keyboard, the mouse, the touch screen and the accelerometer. In the most common scenarios, the desktop machines will not have an accelerometer, and the tablet computers will not have a constantly attached keyboard and a mouse. In FallFury, I decided to leverage all potential input engines and let the user choose the best option for himself. When the current GamePlayScreen instance loads, I am attempting to get access to the system accelerometer device: m_systemAccelerometer = Windows::Devices::Sensors::Accelerometer::GetDefault(); m_systemAccelerometer is of type Windows::Devices::Sensors::Accelerometer and is declared in GamePlayScreen.h. If an accelerometer is detected, I need to bind it to a ReadingChanged event handler that will give me the current G-force transformed into X, Y, and Z displacement: if (m_systemAccelerometer != nullptr) { m_systemAccelerometer->ReadingChanged += ref new TypedEventHandler<Accelerometer^, AccelerometerReadingChangedEventArgs^> (this, &GamePlayScreen::AccelerometerReadingChanged); } ReadingChanged itself does not participate in updating the position for the character, but rather passes the current values to m_xAcceleration, which is later used in the Update method: void GamePlayScreen::AccelerometerReadingChanged(_In_ Accelerometer^ accelerometer, _In_ AccelerometerReadingChangedEventArgs^ args) { if (StaticDataHelper::IsAccelerometerEnabled) { auto currentOrientation = DisplayProperties::CurrentOrientation; float accelValue; if (currentOrientation == DisplayOrientations::Portrait) accelValue = args->Reading->AccelerationY; else if (currentOrientation == DisplayOrientations::PortraitFlipped) accelValue = -args->Reading->AccelerationY; else if (currentOrientation == DisplayOrientations::Landscape) accelValue = args->Reading->AccelerationX; else if (currentOrientation == DisplayOrientations::LandscapeFlipped) accelValue = -args->Reading->AccelerationX; else accelValue = 0.0f; if (StaticDataHelper::IsAccelerometerInverted) m_xAcceleration = -accelValue; else m_xAcceleration = accelValue; } } The reason for this lies in the fact that ReadingChanged is triggered at a much lower rate than the Update loop. If the character position would be adjusted through the core accelerometer event handler, the result would be choppy (“step-by-step”) movement instead of a smooth transition. Notice, also, that depending on the screen orientation, I need to get the acceleration either on the X- or Y-axes. Since an accelerometer is detected, I am assuming that the device that’s being used is a tablet. Therefore, it can have auto-rotate enabled, which means that the reference axis (horizontal) might change depending on how the user holds the device. DisplayProperties::CurrentOrientation can give me the current orientation, whether portrait (Y acceleration value) or landscape (X acceleration value): image As with many other titles, the user may invert the movement based on the accelerometer reading. For example, if the device is tilted to the right, the character will move to the left, and vice-versa. The effect is easily achieved by negating the current reading, regardless of the axis it is relying on. Obviously, as the character moves, there should be boundaries that restrict the movement within the context of the current game screen. To get the correct screen bounds, GameScreenBase, the foundation class for every screen, sets four properties: LoBoundX, HiBoundX, LoBoundY and HiBoundY: LoBoundX = (rWidth - 768.0f) / 2.0f; HiBoundX = LoBoundX + 768.0f; LoBoundY = 0; HiBoundY = LoBoundY + rHeight; LoBoundX is the leftmost limit for the horizontal playable area and HiBoundX is the rightmost limit for the same horizontal area. LoBoundY and HiBoundY are responsible for carrying the limits for the vertical space. All four boundary values are relative to the screen size: image To consistently get the correct X boundary no matter the screen size, the playable area is set to a fixed width of 768 pixels. The rest of the screen is accordingly cancelled out and the remaining area split in two. The original X point (zero) is added to the curtain size and that way there is the leftmost X boundary. The Y boundaries are simply obtained from the screen height, as there are no gameplay experience restrictions in that domain. The bear position is updated in the Update loop in the game screen. There are several parameters that need to be adjusted, such as the vertical velocity, the bear rotation on tilt and the horizontal displacement. When the level just starts, the bear falls faster until he reaches the standard static Y point. Because of screen size differences, this should not be done by comparing the pixel distance but rather by utilizing a ratio built from the current bear Y position and the high Y boundary: if ((GameBear->Position.y / HiBoundY) < 0.19f) { GameBear->Position.y += GameBear->Velocity.y * (3.2f); } Assuming that the game is not paused, and thus the background is moving, the bear Y position should be adjusted relative to the current velocity set for the background scrolling. Because of how parallax scrolling works, the bear velocity has to be higher than the initial screen movement. Therefore, it is multiplied by a fixed value independent of the level played: if (!m_isBackgroundMoving) { if (GameBear->Position.y > m_screenSize.y) { Manager->CurrentGameState = GameState::GS_GAME_OVER; } else { GameBear->Position.y += GameBear->Velocity.y * 1.5f; } } In the statement above, there is also an extra condition that verifies whether the bear is below the low Y boundary. If it is, then the game is over. This is imposed by a game animation that takes the bear off the Y limits, meaning that the bear is dead. Bear rotation is based on the current X acceleration, but the bear shouldn’t rotate 360 degrees. To limit the rotation, there is a rotation threshold set (value taken in radians) that is being checked before rotating the character: float compositeRotation = GameBear->Rotation - (float)m_xAcceleration / 10.0f; if (compositeRotation < m_rotationThreshold && compositeRotation > -m_rotationThreshold) GameBear->Rotation = compositeRotation; The composite value lets me verify the perspective rotation without actually assigning it to the bear. If it is within the imposed threshold, only then will the bear rotation be adjusted. Using the composite value approach is also efficient when performing the horizontal displacement adjustment. The initial value is composed of the current position and the X-based acceleration multiplied by a dynamic multiplier value to create the inertia effect: float compositePosition = GameBear->Position.x + ((float)m_xAcceleration * m_accelerationMultiplier); if (m_xAcceleration < 0) compositePosition -= 100.0f; else compositePosition += 100.0f; if (Manager->IsWithinScreenBoundaries(float2(compositePosition, GameBear->Position.y))) { GameBear->Position.x += (float)m_xAcceleration * m_accelerationMultiplier; } else { if (GameBear->Position.x > HiBoundX) { GameBear->Position.x = HiBoundX - 180.0f; } else if (GameBear->Position.x < LoBoundX) { GameBear->Position.x = LoBoundX + 180.0f; } } If the bear is attempting to hit a “wall” (screen limit), its position is set back to the one barely prior to the limit. By doing this, I am avoiding locking the character on the side of the screen. There is something in this snippet above that you might not be aware of—a reference to Manager->IsWithinScreenBoundaries. This method belongs to the ScreenManager (ScreenManager.cpp) class—a utility class that ensures the proper screen is displayed depending on the current game mode, and also allows control of mouse actions and boundary checks: bool ScreenManager::IsWithinScreenBoundaries(float2 position) { if (position.x < CurrentGameScreen->LoBoundX || position.x > CurrentGameScreen->HiBoundX || position.y < CurrentGameScreen->LoBoundY || position.y > CurrentGameScreen->HiBoundY) return false; else return true; } You saw how the movement is accomplished with the help of the accelerometer. Let’s take a look at how a keyboard can be used to do the same thing. There is a HandleKeyInput method, exposed through the GamePlayScreen class. As a matter of fact, HandleKeyInput is wired into the GameScreenBase class, therefore if a specific combination needs to be handled outside the context of the game play screen, it can be: void GamePlayScreen::HandleKeyInput(Windows::System::VirtualKey key) { if (key == Windows::System::VirtualKey::Right) { if (GameBear->IsWithinScreenBoundaries(GameBear->Size.x, 0.0f, GetScreenBounds())) { GameBear->Direction = TurningState::RIGHT; m_xAcceleration = 0.8f; if (GameBear->Rotation >= -m_rotationThreshold) GameBear->Rotation -= 0.02f; } } else if (key == Windows::System::VirtualKey::Left) { if (GameBear->IsWithinScreenBoundaries(-GameBear->Size.x, 0.0f, GetScreenBounds())) { GameBear->Direction = TurningState::LEFT; m_xAcceleration = -0.8f; if (GameBear->Rotation <= m_rotationThreshold) GameBear->Rotation += 0.02f; } } } As the accelerometer is no longer influencing the rotation or displacement, both indicators have to be manipulated through key presses. There are still standard thresholds in place to limit the potential incorrect movement, but the idea remains the same. This method is being called from the XAML page, which is overlaid on top of the DirectX renders: <SwapChainBackgroundPanel x:Class="Coding4Fun.FallFury.DirectXPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:Coding4Fun.FallFury" x:Name="XAMLPage" xmlns:controls="using:Coding4Fun.FallFury.Controls" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" Loaded="OnLoaded" KeyDown="OnKeyDown" LayoutUpdated="XAMLPage_LayoutUpdated"> void DirectXPage::OnKeyDown(Platform::Object^ sender, Windows::UI::Xaml::Input::KeyRoutedEventArgs^ e) { m_renderer->CurrentGameScreen->HandleKeyInput(e->Key); } When the keyboard is not available, movement can be controlled with the help of a mouse. Again, with standard event handlers, I am simply using OnPointerMoved: void GamePlayScreen::OnPointerMoved(Windows::UI::Core::PointerEventArgs^ args) { if (StaticDataHelper::IsMouseEnabled) { if (GameBear != nullptr) { m_touchCounter++; if (GameBear->IsWithinScreenBoundaries(GameBear->Size.x, 0.0f, GetScreenBounds())) { m_xAcceleration = (args->CurrentPoint->RawPosition.X - GameBear->Position.x) / m_screenSize.x; } } } } By using this method, the bear will accelerate to the point where the mouse cursor is located, having a higher velocity the further it is located from the cursor. Once again, this creates the inertia visualization. Conclusion Concluding Part 3 of the series, remember that because Windows 8 is not a tablet-only OS, some users might have different input devices. Try to accommodate as many of those as possible. The next article in this series will focus on the XAML overlay used in FallFury. ]]> https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-3-Basic-Rendering-and-Movement Continuing the FallFury series, in this article I talk about basic game element rendering and character movement. As you already know, the FallFury user experience stack is split across two layers—native DirectX and XAML. Here, I will only be talking about the native DirectX component. Check out the video for this article at https://channel9.msdn.com/Series/FallFury/Part-3-Basic-Rendering-and-Movement For a complete, offline version of this series, you may download a nicely formatted PDF of all the articles. The BackgroundEach game screen in FallFury has a moving background that creates the illusion of a fall. The way the screen is designed, it simulates vertical parallax scrolling, as the background moves faster than the overlaid objects. There is a simple way to make background movement possible without actually having to replicate parts of the texture and render them all over again. Take a look at this image, showcasing the process: First of all, two textures are loaded that, connected at the bottom, create the illusion of a single texture. In the beginning, texture A takes the entire screen and texture B is positioned directly underneath it, with a non-existing gap between them. To initiate the scrolling, texture A is being displaced vertically by an arbitrary number of pixels, and texture B follows it at the same pace. As texture B reaches the zero point (top of the viewport), texture A is no longer visible, therefore it is displaced vertically to be below texture B. This cycle can be repeated as many times as necessary during gameplay as well as while the user is in the menu. Let’s take a look at the code that makes it possible, starting with the main menu screen: First of all, you need to be aware that every game screen is automatically inheriting the properties and capabilities of base class GameScreenBase. This is the class the offers the foundation both for basic texture loading and movement: protected private: // Core background textures M https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-3-Basic-Rendering-and-Movement Wed, 23 Jan 2013 23:57:03 GMT https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-3-Basic-Rendering-and-Movement Brian Peek, Clint Rutkas, Dan Fernandez, Den Delimarsky, Rick Barraza Brian Peek, Clint Rutkas, Dan Fernandez, Den Delimarsky, Rick Barraza 0 https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-3-Basic-Rendering-and-Movement/RSS C# C++ DirectX Windows Store App Fall Fury: Part 2 - Shaders Introduction to Shaders FallFury not only relies on standard C++/C# and XAML code, but also on shaders. This article is intended for developers who are not aware of what shaders are and want to know how to use them in their projects. I will talk about creating shaders, as well as the shaders used in my project. Check out the video for this article at https://channel9.msdn.com/Series/FallFury/Part-2-Shaders.  For a complete, offline version of this series, you may download a nicely formatted PDF of all the articles. Code on GPU In simple terms, shaders are small programs that are executed on the Graphical Processing Unit (GPU) instead of the Central Processing Unit (CPU). In recent years, we’ve seen a major spike in the capabilities of graphic devices, allowing hardware manufacturers to design an execution layer tied to the GPU, therefore being able to target device-specific manipulations to a highly optimized unit. Shaders are not used for simple calculations, but rather for image processing. For example, a shader can be used to adjust image lighting or colors. Modern GPUs give access to the rendering pipeline that allows developers to execute arbitrary image processing code. This is a step forward from a fixed-function pipeline that was present in older GPUs, where image processing tasks were integrated into the hardware unit and were only able to perform a limited set of actions, such as transforms. Unlike the rendering pipeline, the fixed-function pipeline was not programmable, therefore the developers were often tied to the hardware they used for offering specific game effects, in some cases having to resort to software-based adjustments. Types of Shaders There are different types of image manipulations that can be performed on a given input, and so there are different types of shaders designed to handle that. Currently, we can highlight three main shader types: • Vertex shaders – because what the user sees on the screen is not really three-dimensional, but rather a three-dimensional simulation in a 2D space, vertex shaders translate the coordinates of a vector in 3D space in relation to the 2D frame. Vertex shaders are executed one time per vector passed to the GPU. Typically, vectors carry data related to their position and the coordinate of the bound texture as well as color. A vertex shader is able to manipulate all these properties, but there is never a situation where a new vertex is created as a result of the execution. • Pixel shaders – these programs are executed on the GPU in relation to every passed pixel, working on a much lower level. For example, if you want specific pixels adjusted for lighting or 3D bump mapping, a pixel shader can provide the desired effect for a surface. Rarely, there are situations where only a few pixels should be re-adjusted at once. Pixel shaders are often run with an input of millions of pixels, resulting in complex effects. • Geometry shaders – these shaders are the next progression from vertex shaders, introduced with DirectX 10. The developer is able to pass specific primitives as input and either have the output represent the modified version of what was passed to the program or have new primitives, such as triangles, be generated as a result. Geometry shaders are always executed on post-vertex processing in the rendering pipeline. When vertex shader execution is completed, geometry shaders step in, if present. Geometry shaders can be used to refine the level of detail of a specific object. For example, when an object is closer or further away from the viewport camera, the mesh would have to be refined to minimize the rendering load. FallFury uses all these shader types as a part of the game. Enough Talk, Let’s Code Now that you are aware of what shaders are, let’s write some sample code and test it. It is worth mentioning that shaders are not written in a standard high-level language, but rather in a language defined by the environment the shader is used in. For Direct3D, this is the High-Level Shader Language, or HLSL. It is somewhat similar to C, but with some specific nuances. Start by creating a test Direct3D Windows Store application: clip_image002 If you create and run this sample application, you will see that the output of it is a simple 3D spinning cube: clip_image004 You probably also noticed that there are two shaders that are a component part of the newly created solution: SimplePixelShader.hlsl and SimpleVertexShader.hlsl. Take a look inside the pixel shader: struct PixelShaderInput { float4 pos : SV_POSITION; float3 color : COLOR0; }; float4 main(PixelShaderInput input) : SV_TARGET { return float4(input.color,1.0f); } First of all, there is a PixelShaderInput struct[DW1] . It represents a single pixel – it has a float4 field that represents the position of the pixel and a float3 field that represents the RGB pixel color. The field itself is also marked by a predefined type, such as SV_POSITION or COLOR. This is a string that determines the use of the field. You can read more about the shader semantics here. The strings that are prefixed with SV_ are representing system-value semantics. Those have special meaning in the pipeline during the processing stages. In the pixel shader above, SV_POSITION will always mean the pixel position. Look at what is being returned from the pixel shader—instead of the standard float3 color indicator, you are now returning a float4, which couples the existing value, input.color, with a 1.0f float value that represents the alpha-channel value. Remember, that inside shaders the color is clamped between 0 and 1 instead of the standard 255-value limit. Since the cube rendering mechanism is already in place, let’s experiment with the pixel shader a bit. You’ve already got the float4 color representation: clip_image006 You can set any of these values to 1.0 to return the solid color, so let’s do that. Let’s render the cube green. Modify the return statement to be this: return float4(0.0, 1.0, 0.0, 1.0); At this point, if you will run the program you will get a rendering very similar to this: clip_image008 This is a good start.. Now, let’s now take a look at the vertex shader in the project. By default, you get this: cbuffer ModelViewProjectionConstantBuffer : register(b0) { matrix model; matrix view; matrix projection; }; struct VertexShaderInput { float3 pos : POSITION; float3 color : COLOR0; }; struct VertexShaderOutput { float4 pos : SV_POSITION; float3 color : COLOR0; }; VertexShaderOutput main(VertexShaderInput input) { VertexShaderOutput output; float4 pos = float4(input.pos, 1.0f); pos = mul(pos, model); pos = mul(pos, view); pos = mul(pos, projection); output.pos = pos; // Pass through the color without modification. output.color = input.color; return output; } There are a couple of differences here compared to the above mentioned pixel shader: • cbuffer ModelViewProjectionConstantBuffer – represents a constant buffer that contains three matrices, to which vertices are related—the model, view and projection matrices. Constant buffers are interesting structures that have been optimized to allow block-wise updates, where multiple constants are grouped in one boxed unit and can be updated simultaneously instead of having a one-by-one iterative update cycle. • struct VertexShaderInput – vertices are passed one-by-one to the shader, and this specific structure represents the input. Notice that it carries the 3D representation of the vertex position as well as its RGB color value. • struct VertexShaderOutput – the final processed output, which now carries the position in relation to all three matrices mentioned above as well as the processed color. Notice that the fourth value is the camera distance in the demo. • VertexShaderOutput main(VertexShaderInput input) – this is the main function that performs the vertex processing. Initially, it performs the position adjustment relative to the camera and then uses mul, a built-in function that multiplies matrices, to represent the current vertices in the projected space. So let’s play around with what we have in stock. Take a look at the main function and how initially, the float3-based position is transformed to contain the camera distance: float4 pos = float4(input.pos, 1.0f); This position is normalized in relation to the current viewport. Afterwards, the vertex is transformed in the current 3D space (relative to three matrices – model, view, and projection): pos = mul(pos, model); pos = mul(pos, view); pos = mul(pos, projection); output.pos = pos; As with the pixel shader, these are some very basic manipulations. Let’s flip the cube upside-down. To do this, we need to apply a rotation transformation. Here is an interesting piece of advice—when working with manipulations in shaders, make sure that you know basic matrix operations. For example, to perform a simple 2D rotation, you need to use the rotation matrix: clip_image009 But since we’re in 3D space, we not only have the X and Y coordinates, which relate to the matrix above, but also the Z coordinate. Therefore, a different method should be applied. There are three fundamental matrices that can be used to rotate an object around the three possible axes: clip_image011 For now, we want to rotate the cube along the X-axis. To do this, inside the main function, we need to declare a constant that represents the rotation angle, in radians: const float angle = 1.3962634; Looking at the matrix above, we need to find out the sine and cosine of the given angle. When working with vertex shaders, HLSL offers a built-in function, called sincos that is able to get both values from an input value: float cosLength, sinLength; sincos(angle, sinLength, cosLength); Now you need to declare the rotation matrix. Again, HLSL comes with some built-in capabilities to declare matrices and set their values: float3x3 xAxisRotation = { 1.0, 0.0, 0.0, // Row 1 0, cosLength, -sinLength, // Row 2 0, sinLength, cosLength}; // Row 3   The standard format for matrix declaration in this case follows the following pattern: Matrix<type,size> localName For matrix multiplication, we can once again leverage the mul function: float3 temporaryPosition; temporaryPosition = mul(input.pos,xAxisRotation); Now we can normalize the position to a float4 value that also includes the camera distance: float4 pos = float4(temporaryPosition, 1.0f); The rest of the transformation procedures can be taken directly from the original shader, multiplying the float4 position by the model, view, and projection matrices. Your entire main function should now look like this: VertexShaderOutput main(VertexShaderInput input) { VertexShaderOutput output; const float angle = 1.3962634; float cosLength, sinLength; sincos(angle, sinLength, cosLength); float3x3 xAxisRotation = { 1.0, 0.0, 0.0, // Row 1 0, cosLength, -sinLength, // Row 2 0, sinLength, cosLength}; // Row 3 float3 temporaryPosition; temporaryPosition = mul(input.pos,xAxisRotation); float4 pos = float4(temporaryPosition, 1.0f); // Transform the vertex position into projected space. pos = mul(pos, model); pos = mul(pos, view); pos = mul(pos, projection); output.pos = pos; // Pass through the color without modification. output.color = input.color; return output; } The current angle is set to 80 degrees, or 1.3962634 radians. If you run the rendering test application, the result you will get will be similar to this: clip_image013 Now, let’s look at how shaders are handled on the DirectX side. Shaders in DirectX Open CubeRenderer.cpp. This is the source file where internal shaders are read and passed to the device to be executed. Notice one interesting aspect of the process – the shader file contents are being read first and then passed to m_d3dDevice->CreateVertexShader. m_d3dDevice is a pointer to a virtual adapter that can be used to create device-specific resources. CreateVertexShader creates a vertex shader from an already compiled shader. You can notice it from the fact that the data is read not from the initial .hlsl file, but rather from the .cso (Compiled Shader Object): auto loadVSTask = DX::ReadDataAsync("SimpleVertexShader.cso"); As with any program, before it is passed onto the execution layer, it has to be compiled first. Visual Studio 2012 comes with a bundled HLSL compiler, fxc—the Effect Compiler Tool. The default behavior for a shader is to be compiled with the .cso file extension in the same output directory as the project, but this can be changed by setting the Object File Name in the shader properties: clip_image015 You can read more about the shader compilation process here. Looking back at the sample vertex shader that was created as a part of the project, you will notice that there is a specific input layout set for the incoming object: struct VertexShaderInput { float3 pos : POSITION; float3 color : COLOR0; };   The virtual adapter is not aware of the structure layout. Therefore, the developer needs to explicitly create an internal D3D11_INPUT_ELEMENT_DESC array that will contain the type of information passed to the shader: const D3D11_INPUT_ELEMENT_DESC vertexDesc[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, };   Once the description is complete, the input needs to be assembled for processing. That’s where CreateInputLayout comes into play: DX::ThrowIfFailed( m_d3dDevice->CreateInputLayout( vertexDesc, ARRAYSIZE(vertexDesc), fileData->Data, fileData->Length, &m_inputLayout ) );   You are basically passing a shader signature to the input assembler that will perform all the consequent processing. A similar process is applied for the existing pixel shader, with the main difference being the fact that instead of CreateVertexShader, CreatePixelShader is called: Passing Custom Parameters to Shaders Going back to our vertex shader where we performed the rotation relative to the X-axis, you probably noticed that the angle is hard-coded and is applied to each vector in the same way. This is rarely the case, as the angle would normally come from inside the game itself, often responding to internal behavior, such as character movement or action. To pass a parameter to the shader, you need to first of all redefine the input structure. Let’s add an angle carrier to the VertexShaderInput struct in SimpleVertexShader.hlsl: struct VertexShaderInput { float3 pos : POSITION; float3 color : COLOR0; float angle : TRANSFORM0; }; This alone won’t do anything. Go the entry point function (main) and make sure that the angle constant is set to input.angle: const float angle = input.angle; Now the shader is ready, but you also need to let your game know that the vertex shader has a modified input layout. To do this, go to CubeRenderer.cpp and find the D3D11_INPUT_ELEMENT_DESC array that defines the input layout for incoming vertex shaders. Simply add an identifying item to the existing array: const D3D11_INPUT_ELEMENT_DESC vertexDesc[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TRANSFORM", 0, DXGI_FORMAT_R32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; The first parameter is the pre-defined semantic used in the shader. The second parameter defines the input index. After that, use DXGI_FORMAT_R32_FLOAT to indicate that the value passed will be a standard float. Pay close attention when you specify the input offset. Notice that the two FLOAT3 values, POSITION and COLOR, take 12 bytes each —a float takes 32 bits (4 bytes), and you have a triplet, therefore the offset for TRANSFORM should be 24 bytes (two times 12 bytes from previous indicators). Now you need to modify the internal vector descriptors that are being passed to the rendering pipe. In the sample project those are created with the help of the VertexPositionColor class, located in the CubeRenderer.h. Add a simple float field to the existing struct, so it looks like this: struct VertexPositionColor { DirectX::XMFLOAT3 pos; DirectX::XMFLOAT3 color; float angle; };   In CubeRenderer.cpp, find the cubeVerticles array. For each created VertexPositionColor you are now able to add a third value representing the rotation: auto createCubeTask = (createPSTask && createVSTask).then([this] () { VertexPositionColor cubeVertices[] = { {XMFLOAT3(-0.5f, -0.5f, -0.5f), XMFLOAT3(0.0f, 0.0f, 0.0f), 1.38f}, {XMFLOAT3(-0.5f, -0.5f, 0.5f), XMFLOAT3(0.0f, 0.0f, 1.0f), 1.38f}, {XMFLOAT3(-0.5f, 0.5f, -0.5f), XMFLOAT3(0.0f, 1.0f, 0.0f), 1.38f}, {XMFLOAT3(-0.5f, 0.5f, 0.5f), XMFLOAT3(0.0f, 1.0f, 1.0f), 1.38f}, {XMFLOAT3( 0.5f, -0.5f, -0.5f), XMFLOAT3(1.0f, 0.0f, 0.0f), 1.38f}, {XMFLOAT3( 0.5f, -0.5f, 0.5f), XMFLOAT3(1.0f, 0.0f, 1.0f), 1.38f}, {XMFLOAT3( 0.5f, 0.5f, -0.5f), XMFLOAT3(1.0f, 1.0f, 0.0f), 1.38f}, {XMFLOAT3( 0.5f, 0.5f, 0.5f), XMFLOAT3(1.0f, 1.0f, 1.0f), 1.38f}, };   Now you will be able to pass parameters to the vertex shader without having to manually modify the shader itself. Shaders in FallFury There are several shaders used in FallFury, which must be selected depending on the Direct3D feature level available on the machine. A feature level determines what a video adapter can do in terms of rendering—even though Direct3D is a unified framework, it still heavily relies on how individual graphic cards can perform. There are 5 shaders used internally for texture rendering. Specifically, there is a pixel shader, a replication vertex shader, an instancing vertex shader and geometry shaders. This could be familiar if you worked with Microsoft DirectX sprite samples before: clip_image016 Given the platform limitations, geometry shaders can only be used on devices supporting Direct3D Feature Level 10. When FallFury detects that the feature level is lower than that, it has to fall back on either the instancing or the replication shaders. Some devices, such as the Microsoft Surface, are at feature level 9.1. Therefore, the replication render technique must be enforced. Following the Microsoft DirectX Sprite Sample, it is fairly easy to simply select the correct render technique once the feature level is detected with GetFeatureLevel: auto featureLevel = m_d3dDevice->GetFeatureLevel(); if (featureLevel >= D3D_FEATURE_LEVEL_10_0) { m_technique = RenderTechnique::GeometryShader; } else if (featureLevel >= D3D_FEATURE_LEVEL_9_3) { m_technique = RenderTechnique::Instancing; } else { m_technique = RenderTechnique::Replication; if (capacity > static_cast<int>(Parameters::MaximumCapacityCompatible)) { // The index buffer format for feature-level 9.1 devices may only be 16 bits. // With 4 vertices per sprite, this allows a maximum of (1 << 16) / 4 sprites. throw ref new Platform::InvalidArgumentException(); } }   Depending on the selected render technique, which is determined on application startup, the proper input layout is selected for each shader and is used to control the rendering pipe. Different graphic adapters also support different shader models. You need to account for those, and before running the application, the HLSL compiler will take on the task of determining whether a proper shader component is supported by the given model. In the shader properties, make sure that you specify the used shader model, as well as the type of the shader: clip_image018 Without this, you are bound to experience compile time errors that will prevent you from launching the application or deploying it to different devices. Conclusion Shaders are not an easy subject. I highly recommend reading The Cg Tutorial, published online for free by nVidia. Even though it describes the Cg shader language, it is virtually identical to HLSL and you will not have any problems using the practices you learned there in building HLSL shaders. ]]> https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-2-Shaders Introduction to ShadersFallFury not only relies on standard C&#43;&#43;/C# and XAML code, but also on shaders. This article is intended for developers who are not aware of what shaders are and want to know how to use them in their projects. I will talk about creating shaders, as well as the shaders used in my project. Check out the video for this article at https://channel9.msdn.com/Series/FallFury/Part-2-Shaders. For a complete, offline version of this series, you may download a nicely formatted PDF of all the articles. Code on GPUIn simple terms, shaders are small programs that are executed on the Graphical Processing Unit (GPU) instead of the Central Processing Unit (CPU). In recent years, we’ve seen a major spike in the capabilities of graphic devices, allowing hardware manufacturers to design an execution layer tied to the GPU, therefore being able to target device-specific manipulations to a highly optimized unit. Shaders are not used for simple calculations, but rather for image processing. For example, a shader can be used to adjust image lighting or colors. Modern GPUs give access to the rendering pipeline that allows developers to execute arbitrary image processing code. This is a step forward from a fixed-function pipeline that was present in older GPUs, where image processing tasks were integrated into the hardware unit and were only able to perform a limited set of actions, such as transforms. Unlike the rendering pipeline, the fixed-function pipeline was not programmable, therefore the developers were often tied to the hardware they used for offering specific game effects, in some cases having to resort to software-based adjustments. Types of ShadersThere are different types of image manipulations that can be performed on a given input, and so there are different types of shaders designed to handle that. Currently, we can highlight three main shader types: Vertex shaders – because what the user sees on the screen is not really three-dimensional, but r https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-2-Shaders Wed, 23 Jan 2013 23:57:00 GMT https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-2-Shaders Brian Peek, Clint Rutkas, Dan Fernandez, Den Delimarsky, Rick Barraza Brian Peek, Clint Rutkas, Dan Fernandez, Den Delimarsky, Rick Barraza 2 https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-2-Shaders/RSS C# C++ DirectX Windows Store App Fall Fury: Part 1 - Introduction In late May, I arrived in Redmond to work as an intern on the Channel9 team. I had the freedom to choose what I was going to work on, so I decided to challenge myself and work outside my comfort zone, utilizing less C# and managed code and more C++ and DirectX. To do so, I decided to highlight the capabilities of Windows 8—that’s how FallFury was born. FallFury is a 2D platformer in which the player controls a falling bear, trying to avoid obstacles, dodge missiles, and destroy monsters as the bear falls. The project incorporates several of the new Windows 8 APIs, including the accelerometer and touch as well as integrations with core OS capabilities such as settings and share charms. Additionally, the project leverages the most exacting addition to the Visual Studio development environment—hybrid application development with XAML, C++, and DirectX. Check out the video for this article at https://channel9.msdn.com/Series/FallFury/Part-1-Introduction.  For a complete, offline version of this series, you may download a nicely formatted PDF of all the articles. Design & Idea From the outset, Rick Barraza and I decided that since our target audience was composed of both kids and adults, the main character had to be familiar to both groups. Teddy bears turned out to be the best choice. Rick spent a day creating tens of potential bear drawings—out of which I had to choose one: clip_image002[5] clip_image004[5] As the bear’s fall progresses, the character encounters a variety of obstacles dependent on the level type and complexity. Those obstacles should of course be avoided, so as the user tilts the device, the character in the game moves in the associated direction. The design of the project took a week, and during this time the following items were determined and conceptualized. Considerations for both tablet and desktop environments directed our decisions: · The main character layout. · The way the game progresses as the character falls down. · How the user interacts with the game in a wide variety of possible scenarios. · What the game screens look like. · What the menu system interaction looks like. · How the game looks in different screen modes and on different device types. · Some of the bonuses that the main character can pick up during free fall. · What happens when the user progresses through the game and iterates through levels. · What is shared and how this is accomplished. As the game ideas were outlined, Arturo Toledo, the designer behind ux.artu.tv, was brought on to create the game assets. Then the core design decisions were made and we jumped into the development process. Beginning the development You will need to download and install Microsoft Visual Studio 2012 Express for Windows 8 in order to be able to follow the steps that I am describing in this series. The development has to be done on Windows 8, because the end result is a Windows Store application that relies on Windows 8 APIs. Though specific hardware is not required, both ARM and x86 devices will work well, so whether you have a Microsoft Surface RT or Samsung Series 7 slate, you will be able to test the code when you have the opportunity. To get started, open Visual Studio 2012 and select the C++ project types. You will notice that there are several options you can choose from. You want to create a Windows Store application, so choose the appropriate category. Windows Store applications run in a sandbox, outside the boundaries of the standard .NET runtime. Next, select the Direct2D (XAML) app type from the project list. This is a new application type introduced in Visual Studio 2012 that allows developers to combine native DirectX graphics with XAML overlays. Do not be confused by the fact that there is a Direct2D in the name—you can still invoke DirectX capabilities supported in the WinRT sandbox: clip_image006[6] At this point you might be wondering, why choose a hybrid application instead of a fully-native project? The reason behind this decision is that is allows the developer to focus more on fine-tuning the gameplay instead of creating the UI core in pure DirectX. Because XAML is a part of the game, we can create dynamic UI layouts for the HUD, settings charm and menus without touching the graphical backbone. It is possible to do the same directly through DirectX and was a perfect approach for FallFury, considering the time constraints and the fact that I needed minimal UI overlays. Most of the graphics were already processed through the DirectX pipeline, so I did not have to invest significant resources and time into designing low-level structures for the interactivity layer. FallFury uses XAML for the following: • Menus – depending on the screen, the user is able to trigger a number of actions. For example, when the game starts, the user might select the New Game option or decide to take a look at the About screen. In Paused mode, the menu is used to resume the game, adjust settings, or possibly skip a level. • Game HUD (score indicator, pick-up indicator, health indicator) – during the gameplay, the user is interested in keeping track of where the character is and what is the state of it. The game HUD is shown in active game mode. • Settings charm extensions – the way the Settings charm works, the OS provides the core harness to hook to the Settings popup. Once shown, it is up to the developer to provide a multitude of options that customize the application behavior; any additional popups shown on selection should be designed individually in XAML. • User notification – when something happens that can potentially affect the gameplay, the user should be alerted. The core framework provides the capabilities to use a MessageDialog, but in some cases it might not be enough. For example, if new levels are available for download, the user might want to check those out in a custom popup including full previews rather than just text. When you create the project, a default infrastructure that prints text on the screen—both through Direct2D and XAML—is available. Direct2D is a subset of DirectX APIs and facilitates hardware-accelerated 2D graphics processing. It is used to create basic geometry elements and text. Since I am here working mostly with XAML, I am not going to cover Direct2D in-depth in this article: clip_image008[5] I will go into more details regarding the XAML and DirectX interaction model later in the series, but for now, take a look at which parts of the project you have available. First and foremost, you probably notice the combination of both C++ source and header files and DirectXPage.xaml. Starting with Visual Studio 2012, you are now able to create XAML applications in C++. So even if you are an experienced C++ developer who never worked with the Extensible Application Markup Language, you can create the product core in your familiar environment and either import existing XAML structures or delegate the XAML writing to a designer. If you open the XAML page, you will notice one significant change that you haven’t experienced in standard XAML applications, such as WPF or Silverlight for Windows Phone: <SwapChainBackgroundPanel x:Name="SwapChainPanel" PointerMoved="OnPointerMoved" PointerReleased="OnPointerReleased"> <TextBlock x:Name="SimpleTextBlock" HorizontalAlignment="Center" FontSize="42" Height="72" Text="Hello, XAML!" Margin="0,0,0,50"/> </SwapChainBackgroundPanel> A SwapChainBackgroundPanel is a component that lets the developer overlay XAML on top of the core DirectX-based experience. Look, for example, at the FallFury main menu as the game runs in landscape mode: clip_image010[6] The menu buttons, the label and the side curtains are designed and rendered entirely in XAML. The clouds in the background, as well as the teddy bear, are rendered directly through the DirectX stack. The end-user does not notice any difference in the way these elements interact or are displayed. From a development perspective, however, there are several conditions that must be met. There can only be one instance of SwapChainBackgroundPanel per app. Therefore, you can have only one overlaid XAML controls set. This does not mean that you can’t have multiple controls, but it implies that to do so you have to implement a control management flow that handles content adaptation. For example, if I invoke the pause state in the game, I don’t show the HUD but rather the screen-specific controls that let me resume or abandon the game and the PAUSE label. This switch needs to be handled on both the DirectX and XAML because a state change affects what is shown on the screen and what behaviors are tracked. As you will see through this series, this is not too hard to implement with a helper class that will store the global game state, that can be accessed from anywhere in the game. When using SwapChainBackgroundPanel, remember that XAML is in all cases overlaid on top of the DirectX renders. So, no matter what controls you are using, those will always be placed on top of what DirectX shows to the user. For more details about how DirectX and XAML interoperate, check out this MSDN article. Assets for the game As with any other game, there is not only code involved in production—there are also sound and graphical assets that create a unique experience for the user. FallFury includes a wide variety of graphical assets designed by Toledo Design as well as audio created by David Walliman. It is important that all graphical resource requirements are established at the very beginning of development. As I mentioned in the Design section of this article, I had to put together a list of all the game screens, power-ups, obstacles, backgrounds, character states and possible particles that were generated from a texture. That way, when the designer started creating the assets, all components blended together well and their styles were compatible with the vision of the game. While working on the assets, Arturo Toledo created multiple variations of the same set up that showed how assets integrate in different game conditions: clip_image012[5] As you follow this series, you will not have to create your own game assets—we at Coding4Fun decided to provide all graphical and audio assets, which you can download at http://fallfury.codeplex.com/.  We not only provided you with the final PNG and DDS files, but also with the raw assets that can be used in Microsoft Expression Design and Adobe Illustrator. Let’s take a look at what is in the package. You will notice that the project Assets folder is split in several subfolders. All these assets are used mostly in the XAML layer or in game conditions where texture/sound processing is not necessary. There is also an additional asset folder I will discuss later. • Backgrounds –the level backgrounds, such as the blue, purple or red sky, as well as the overlays, such as clouds that move simultaneously with the backgrounds. Each background/overlay combination is assigned to a specific level type. • Bear – some of the bear elements that are displayed at different times in the game, such as when the game is over or when the player wins the entire level set. • HUD – basic elements that are displayed during the game. • Icons – the application icons, in a variety of sizes, required for a Windows Store application. • Medals – winning players are awarded a medal. It can be golden, silver, or bronze. • Misc – you get some branding elements as well as some graphics that are used in combination with other game items, such as particles. • Monsters – monsters are used in the “How To” part of the game. • Music – the long tracks used in different levels and screens. • Sounds – short sound clips used when different game behaviors in the game are triggered. For example, when the bear gets hit, he lets out a brief cry. All graphical assets mentioned here are PNG resources. The way I structured the game, some elements are larger than the others and I needed to take some measures to cut down on the package size. PNGs are fairly well-sized without much quality loss compared to raw images. At the beginning of the development process, all graphics were stored in DDS files. DirectDraw Surface, or DDS, is a file format developed by Microsoft that helps developers optimize some of the graphics by avoiding re-compression performance loss. One of the benefits of using DDS files is the fact that whenever they are processed by the GPU, the amount of memory taken by them is the same as the file size of the DDS file itself. Usually, for 2D games the compression-based performance loss is not necessarily noticeable. For PNG files used on the DirectX stack, resources are allocated to decompress the texture. Not so for DDS files. Depending on the case, DDS files can be generated on the fly. FallFury preserves relatively small textures in DDS format and larger ones, such as backgrounds, in PNG. It’s the best of both worlds. DDS files can be generated by a tool bundled with the DirectX SDK called dxtex (usually located in C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Utilities\bin\x64): clip_image014[5] There is also texconv that allows you to create DDS components from the command line, but we’ll explore that later in the series. All DDS assets are located in the DDS folder in the solution. All that’s there are assets related to levels, such as obstacles, and assets related to character behavior, such as bear states and used weapons and powerups. Unlike graphic assets that can be mocked from the very start, audio assets are a bit harder to come up with, mainly because at that point you need to be sure what the game will be like at the end. Music and effects should go together with the overall game feel. There are two types of audio components in FallFury—the music and the action-based sound effects. Music is played constantly, whether in the game or on a game screen such as the main menu, unless disabled by the user. The way the audio engine works in FallFury, files are handled differently depending on where in the game they are used. All music is stored in MP3 files and the short sound effects are stored in uncompressed WAV files. As a part of the new project that you are creating, replicate the folder structure for the Assets and DDS folders and add them to the solution. The way C++ project references work, you might want to switch to the “Show All Files” mode in the Solution Explorer: clip_image015[5] Then, simply copy the folders to the solution folder itself. That way you will have all these resources as a part of the project itself and not just links to external files. Source Control It’s a really good idea to use source control. There are multiple options available at no cost, such as CodePlex, Assembla, and Team Foundation Service. You need source control for multiple reasons. The most important reason of them all, however, is that code will break. There were multiple situations where I changed parts of the project and all of a sudden some components stopped working. With the project hooked to a source control system, all I needed was to do a quick rollback to the previous check-in and I was good to go. A good practice I learned from Clint Rutkas is performing atomic check-ins. When something goes wrong, it is much easier to go back to the check-in where only 20 or 30 code lines were modified from what is currently in the stack, compared to going back to the solution where you will be missing two or more entire source files. Modular Design & Prototyping As you are following this project creation from scratch, notice how the entire code base is modular and interchangeable. If I decide to create a new game screen, I can do so easily by inheriting from an existing base class that provides the basic harness. If I want to replace a character model, I can do so by modifying a single class without breaking the entire interaction model. Prototyping is also a big part of FallFury and it is key that no time is wasted working on features that will have to be entirely replaced or re-written. A good example to this scenario happened just as I started writing the project code. I noticed that the Settings charm required some XAML work for secondary popups that extended from the OS-invoked layer. As I was working on a pure DirectX application, I had to create the XAML in code-behind and that was one of the experiences that could’ve been avoided in a hybrid application. During the prototyping stage it is easy to spot potential integration problems and later change parts of the project to work better together. It is much more complicated to replace project components when the core is wired-in than when you have small parts that independently show how a part of the game works. Hardware As you are about to start writing large amounts of code, you are probably wondering whether actual hardware is needed to test the application. The way FallFury was designed, you will be able to run it on any Windows 8 compatible machine, whether a desktop computer or a tablet. If the game is being run on the desktop, I assume that you probably do not have access to an accelerometer or a touch display. If you are running the game on the tablet, you probably do not have a physical keyboard constantly attached to it. These facts ultimately affect how you experience the game itself. From a development perspective, it is important to have multiple types of target hardware available, because the game might behave differently depending on the device configuration. But it is not required to follow this article series. As long as you have a Windows 8 machine, you are good to go. Conclusion Now onto 11 more articles on how to build Fall Fury!   For a complete, offline version of this series, you may download a nicely formatted PDF of all the articles! ]]> https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-1-Introduction In late May, I arrived in Redmond to work as an intern on the Channel9 team. I had the freedom to choose what I was going to work on, so I decided to challenge myself and work outside my comfort zone, utilizing less C# and managed code and more C&#43;&#43; and DirectX. To do so, I decided to highlight the capabilities of Windows 8—that’s how FallFury was born. FallFury is a 2D platformer in which the player controls a falling bear, trying to avoid obstacles, dodge missiles, and destroy monsters as the bear falls. The project incorporates several of the new Windows 8 APIs, including the accelerometer and touch as well as integrations with core OS capabilities such as settings and share charms. Additionally, the project leverages the most exacting addition to the Visual Studio development environment—hybrid application development with XAML, C&#43;&#43;, and DirectX. Check out the video for this article at https://channel9.msdn.com/Series/FallFury/Part-1-Introduction. For a complete, offline version of this series, you may download a nicely formatted PDF of all the articles. Design &amp; IdeaFrom the outset, Rick Barraza and I decided that since our target audience was composed of both kids and adults, the main character had to be familiar to both groups. Teddy bears turned out to be the best choice. Rick spent a day creating tens of potential bear drawings—out of which I had to choose one: As the bear’s fall progresses, the character encounters a variety of obstacles dependent on the level type and complexity. Those obstacles should of course be avoided, so as the user tilts the device, the character in the game moves in the associated direction. The design of the project took a week, and during this time the following items were determined and conceptualized. Considerations for both tablet and desktop environments directed our decisions: · The main character layout. · The way the game progresses as the character falls down. · How the user interacts with the game https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-1-Introduction Wed, 23 Jan 2013 23:56:55 GMT https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-1-Introduction Brian Peek, Clint Rutkas, Dan Fernandez, Den Delimarsky, Rick Barraza Brian Peek, Clint Rutkas, Dan Fernandez, Den Delimarsky, Rick Barraza 9 https://channel9.msdn.com/coding4fun/articles/Fall-Fury-Part-1-Introduction/RSS C# C++ Windows Store App Maelstrom: An Overview For //build/ 2012, we wanted to showcase what Windows 8 can offer developers.  There are a lot of projects showing off great things like contracts and Live Tiles, but we wanted to show off some of the lesser known features.  This project focuses on one of those: stereoscopic 3D with DirectX 11.1. Prior to DirectX 11.1, stereoscopic 3D required specific hardware and a custom API written for that hardware.  With DX11.1, stereoscopic 3D has been "democratized."  Any GPU that supports DirectX 11.1 can be connected to any device which supports stereoscopic 3D, be it a projector, an LCD TV, or anything else.  Plug it in and DirectX does the rest. From the software side of things, any DX11.1 application can determine if the connected display supports stereoscopic 3D, and choose to render itself separately for the player's left and right eye. To showcase this feature, we decided to build a very simple game that would give the illusion of depth, but be easy to explain and play.  What's easier than Pong?  So, we built the world's most over-engineered game of 3D Pong named Maelstrom. WP_000414 Software Each player setup consists of two applications: the DirectX 11.1 game written in C++, and the touch-screen controller written in C#/XAML.  Both are Windows Store applications.  Since this is a two player game, there are two instances of each application running, one per player.  All for applications are networked together using StreamSockets from the Windows Runtime.  The two controllers and player two's DirectX game connect to player one's DirectX game, which acts as the "master".  Controller input is sent here, and, once the ball and paddle positions are calculated, the data is drawn for player one and sent to player two which draws the world from the other player's perspective. image Direct3D Application Getting Started with stereoscopic DirectX11, C++, and XAML If you have never worked with DirectX before, it can be a little overwhelming at first. And even if you have worked with it some in the past, targeting the new Windows 8 ecosystem, along with C++ and XAML have added some additional changes in how you may have designed your solution previously. Fortunately, the Windows Dev Center for Windows Store Apps has some great samples to get you started, and we took full advantage of them to get to speed. For a great, simple example of how to leverage the new stereoscopic feature in Direct3D 11.1, we started with Direct3D Stereoscopic Sample which shows the basic adjustments to the Render loop for toggling your virtual cameras. However, to see a great example of a simple game structure that also leverages stereoscopic rendering where available, the tutorial found at Walkthrough: a simple Windows Store game with DirectX is invaluable. Further in this article, we will dive deeper into the specifics of stereoscopic rendering in our game. One thing to note, if you follow the link in the above Walkthrough to the original project, it will take you to a C++ only implementation of the game. Now, of course, all the DirectX game objects such as the paddle, puck and walls are all rendered using D3D. However, for HUD (Heads up Display) elements, this C++ only sample also uses DirectX exclusively. If you are coming from a managed code background, this will definitely seem like unnecessary overhead. That is because this C++ only sample was created after last year's BUILD conference in 2011 and C++ and DirectX still did not play well with XAML. However, a few months later, the ability to nest DirectX content in a XAML project became available for true hybrid style solutions (see the article DirectX and XAML interop - Windows Store apps using C++ and DirectX for more information). After this feature was added, the simple Shooter Game referenced above had its HUD logic rewritten in XAML and posted up to Dev Center as XAML DirectX 3D shooting game sample, which shows both stereoscopic support, a simple Game Engine structure in C++ and XAML integration. At this point, we had all the starter code we needed to start writing our own game. Game Engine We modified the base sample to accommodate our needs.  We created specific GameObjects, such as Paddle, Puck, etc. to add the behaviors we needed.  We also added an Update and Render method to the base GameObject so that, for every frame, we could do any calculations required, and then draw the object to the screen.  This is very similar to how XNA sets up its game engine. Game Constants Because we were tweaking a variety of values like colors, sizes, camera locations, etc., we created a GameConstants.h header file which contains nothing but these types of values in a single location.  This made it very easy for us to quickly try out various tweaks and see the results on the next run.  Using namespaces helped keep the code a bit more manageable here as well.  Here’s a quick snippet of that file: namespace GameConstants { // bounds of the arena static const DirectX::XMFLOAT3 MinBound = DirectX::XMFLOAT3( 0.0f, 0.0f, 0.0f); static const DirectX::XMFLOAT3 MaxBound = DirectX::XMFLOAT3(19.0f, 10.0f, 90.0f); // game camera "look at" points static const DirectX::XMFLOAT3 LookAtP1 = DirectX::XMFLOAT3(9.5f, 5.0f, 90.0f); static const DirectX::XMFLOAT3 LookAtP2 = DirectX::XMFLOAT3(9.5f, 5.0f, 0.0f); // Waiting Room camera positions static const DirectX::XMFLOAT3 WaitingEyeP1 = DirectX::XMFLOAT3(GameConstants::MaxBound.x/2, GameConstants::MaxBound.y/2, GameConstants::MaxBound.z - 12.0f); static const DirectX::XMFLOAT3 WaitingEyeP2 = DirectX::XMFLOAT3(GameConstants::MaxBound.x/2, GameConstants::MaxBound.y/2, GameConstants::MinBound.z + 12.0f); static const DirectX::XMFLOAT3 WaitingEyeMjpegStation = DirectX::XMFLOAT3(GameConstants::MaxBound.x/2, GameConstants::MaxBound.y/2, GameConstants::MinBound.z + 9.6f); // game camera eye position static const DirectX::XMFLOAT3 EyeP1 = DirectX::XMFLOAT3(GameConstants::MaxBound.x/2, GameConstants::MaxBound.y/2, GameConstants::MinBound.z - 6.0f); static const DirectX::XMFLOAT3 EyeP2 = DirectX::XMFLOAT3(GameConstants::MaxBound.x/2, GameConstants::MaxBound.y/2, GameConstants::MaxBound.z + 6.0f); static const float Paddle2Position = MaxBound.z - 5.0f; namespace PaddlePower { // power level to light paddle at maximum color static const float Max = 9.0f; // max paddle power color...each component will be multiplied by power factor static const DirectX::XMFLOAT4 Color = DirectX::XMFLOAT4(0.2f, 0.4f, 0.7f, 0.5f); // factor to multiply mesh percentage based on power static const float MeshPercent = 1.2f; }; // time to cycle powerups namespace Powerup { namespace Split { static const float Time = 10.0f; static const float NumTiles = 4; static const DirectX::XMFLOAT4 TileColor = DirectX::XMFLOAT4(0.1f, 0.4f, 1.0f, 1.0f); static const float TileFadeUp = 0.20f; static const float TileDuration = 2.10f; static const float TileFadeDown = 0.20f; static const float TileMeshPercent = 2.0f; static const float TileDiffusePercent = 2.0f; }; }; } Stereoscopic 3D Direct3D must be initialized properly to support stereoscopic displays.  When the swap chains are created, an additional render target is required, such that one render target is for the left eye, and one render target is for the right eye.  Direct3D will let you know if a stereoscopic display is available, so you can create the swap chain and render targets appropriately. With those in place, it’s simply a matter of rendering your scene twice, once per eye…that is, once per render target. For our game this was very simple.  Our in-game camera contains two projection matrices, one representing the view from the left eye, and one from the right eye.  These are calculated when the projection parameters are set. void Camera::SetProjParams( _In_ float fieldOfView, _In_ float aspectRatio, _In_ float nearPlane, _In_ float farPlane ) { // Set attributes for the projection matrix. m_fieldOfView = fieldOfView; m_aspectRatio = aspectRatio; m_nearPlane = nearPlane; m_farPlane = farPlane; XMStoreFloat4x4( &m_projectionMatrix, XMMatrixPerspectiveFovLH( m_fieldOfView, m_aspectRatio, m_nearPlane, m_farPlane ) ); STEREO_PARAMETERS* stereoParams = nullptr; // Update the projection matrix. XMStoreFloat4x4( &m_projectionMatrixLeft, MatrixStereoProjectionFovLH( stereoParams, STEREO_CHANNEL::LEFT, m_fieldOfView, m_aspectRatio, m_nearPlane, m_farPlane, STEREO_MODE::NORMAL ) ); XMStoreFloat4x4( &m_projectionMatrixRight, MatrixStereoProjectionFovLH( stereoParams, STEREO_CHANNEL::RIGHT, m_fieldOfView, m_aspectRatio, m_nearPlane, m_farPlane, STEREO_MODE::NORMAL ) ); } Depending on which eye we are rendering, we grab the appropriate projection matrix and pass it down to the vertex shader, so the final scene is rendered offset for the proper eye. Collision Detection If you are just starting to move into 3D modeling and programming, one of the trickier aspects of your game can be collision detection and response. Maelstrom uses primitives for all of the game elements, so our collision code was able to be a bit more straightforward compared to complex mesh collisions, but understanding a few core math concepts is still critical to grasp what the code is doing. Fortunately, DirectX provides us with an DirectX Math Library that is able to do the serious heavy lifting, so the main complexity comes from framing the problem and learning how to apply the library. For example, In our situation we had up to three very fast moving spheres and needed to check for wall collisions and then handle to appropriate bounce, since some of the walls would also be angled. In a 2D game, a collision detection between a sphere and an axis line is very easy. If the distance between a circle and the line is less than or equal to the radius of the sphere, they are touching. On every frame, you move your circle based on its velocity and do your collision test again. But even here, your solution may not be that easy for two reasons. First, what if the line is angled and not lying flat on the X or Y axis? You have to find the point on the line based on the line's angle that is closest to the sphere to do your distance calculations. And if you then want it to bounce, you have to rotate the velocity of the circle by the line's angle, calculate your bounce, and then rotate back. And that's just rotated walls in 2D. When you move up to 3D, you have to take into account the surface normal  (which way the 3D plane is facing) in your calculations. The second complexity that we needed to account for and which pops up in either 2D or 3D collision detection is travel between frames. In other words, if your ball is travelling very fast, it may have completely travelled through your collision boundary in between frames and you wouldn't notice it if you are only doing a distance / overlap check as outlined above. In our case, the pucks had the ability of travelling very fast with a speed boost, so we needed a more robust solution. Therefore, instead of implementing a simple sphere plane intersection test, we needed to create a line of motion that represented where the ball ended on the previous frame and where it currently is after it's new velocity is added to it's position. That line then needs to first be tested to see if it crosses a WallTile. If it does cross, then we know an collision has occurred between frames. We then solve for the time (t) between frames the Sphere would have first made contact to know the exact point of impact and calculate the appropriate "bounce off" direction. The final code for a puck (or moving sphere) and wallTile collision test looks like this: bool GameEngine::CheckWallCollision(Puck^ puck) { bool isIntersect = false; bool wallCollision = false; for(unsigned int i = 0; i < m_environmentCollisionWalls.size(); i++) { WallTile^ wall = m_environmentCollisionWalls[i]; float radius = puck->Radius(); float signedRadius = puck->Radius(); float contactTime = 0.0f; XMVECTOR contactPlanePoint = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f); XMVECTOR contactPuckPosition = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f); bool intersectsPlane = false; // Determine the velocity of this tick by subtracting the previous position from the proposed current position. // in the previous update() cycle, puck->Position() = puck->OldPosition() + ( puck->velocity * timerDelta ). // Therefore, this calculated velocity for the current frame movement differs from the stored velocity // since the stored velocity is independent of each game tick's timerDelta. XMVECTOR puckVectorVelocity = puck->VectorPosition() - puck->OldVectorPosition(); float D = XMVectorGetX( XMVector3Dot( wall->VectorNormal(), wall->VectorPosition() ) ); // Determine the distance of the puck to the plane of the wall. float dist = XMVectorGetX( XMVector3Dot(wall->VectorNormal(), puck->OldVectorPosition() )) - D; signedRadius = dist > 0 ? radius : -radius; // if the distance of the puck to the plane is already less than the radius, the oldPosition() was intersecting already if ( fabs(dist) < radius ) { // The sphere is touching the plane. intersectsPlane = true; contactTime = 0.0f; contactPuckPosition = puck->OldVectorPosition(); contactPlanePoint = puck->OldVectorPosition() + wall->VectorNormal()*XMVectorSet(signedRadius,signedRadius,signedRadius,1.0f); } else { // See if the time it would take to cross the plane from the oldPosition() with the current velocity falls within this game tick. // puckVelocityNormal is the amount of force from the velocity exerted directly toward the plane. float puckVelocityNormal = XMVectorGetX(XMVector3Dot(wall->VectorNormal(), puckVectorVelocity )); // if the puckvVelocityNormal times the distance is less than zero, a plane intersection will occur if ( puckVelocityNormal * dist < 0.0f ) { // determine the contactTime, taking into account the shell of the sphere ( position() + radius ) // is what will make contact, not the position alone. contactTime = (signedRadius - dist) / puckVelocityNormal; // if the contact time is bewteen zero and one, the intersection has occured bewteen oldPosition() and position() if ( contactTime > 0.0f && contactTime < 1.0f ) { intersectsPlane = true; // this is the position of the puck when its shell makes contact on the plane contactPuckPosition = puck->OldVectorPosition() + XMVectorScale(puckVectorVelocity, contactTime); // this is the position on the plane where the shell touches. contactPlanePoint = contactPuckPosition - XMVectorScale(wall->VectorNormal(), signedRadius); } } } // If the puck has contacted the wall plane, determine if the point of contact falls within the wall boundary for true contact. if (intersectsPlane) { float Kr = 1.0f; // Kr is the coefficient of restitution. At 1.0, we have a totally elastic bounce with no dampening. At Kr = 0.0, the ball would stop at the wall. // Make sure the puck velocity and wall normal are facing each other float impact = XMVectorGetX ( XMVector3Dot ( wall->VectorNormal(), puck->VectorVelocity()) ); if (impact < 0.0f) { wallCollision = true; //// bounce the vector off the plane XMVECTOR VectorNormal = XMVector3Dot(wall->VectorNormal(), puck->VectorVelocity())*wall->VectorNormal(); XMVECTOR VectorTangent = puck->VectorVelocity() - VectorNormal; puck->Velocity(VectorTangent - (XMVectorScale(VectorNormal, Kr))); puck->Position(contactPuckPosition); int segment = (int)(puck->Position().z / GameConstants::WallSegmentDepth); segment = max(min(segment, GameConstants::NumWallSegments-1), 0); auto tiles = m_wallTiles[segment]; WallTile^ tile = tiles[i]; if(tile->GetPowerup() == Powerup::Split) SplitPucks(); break; } } } return wallCollision; } Drawing Maelstrom To draw the game, we wanted to use some advanced techniques. We decided to go with a light pre-pass deferred rendering pipeline with normal mapping. That’s a lot of jargon but it isn’t all that complicated once you know what the jargon means, so let’s break it down. When you draw something in 3D, there are three things that come together to determine the final color of each pixel on the screen: meshes, materials, and lights. A mesh is a collection of triangles that make up a game object (such as a wall tile in Maelstrom). On its own, a mesh is just a bunch of dots and lines. A material makes a mesh look like something. It could be as simple as a solid color but usually it’s a texture and sometimes it’s more (the wall tiles in Maelstrom use both a texture and a normal map to define their material properties). Lastly, lights transform materials by determining how bright they should appear and what sort of tint, if any, they should have. Without lights you would either have complete darkness or you would have flat lighting (where everything has a uniform brightness and adding a tint color would uniformly tint everything on the screen). Forward Rendering vs. Deferred Rendering vs. Light Pre-Pass Rendering The simplest approach to drawing 3D graphics is something called forward rendering. With forward rendering, drawing consists of rendering the mesh and calculating its material and all the lights that affect the material all at the same time. The more lights you add, the more complicated your shaders become since you have to determine whether each light affects the material and if so how much. (Ok, so there’s also multi-pass forward rendering, but that has its own problems – more passes mean longer render times and thus a lower frame rate – and we wanted to keep the descriptions simple). In the last 5 years, many games started using a technique called deferred rendering. In classic deferred rendering, there are two rendering passes. The first pass renders the positions, normals, and material values of all the meshes in the scene to something called a G-Buffer (two or more render targets); nothing is actually drawn to the screen in this first pass. The second pass uses the data from the G-Buffer (which tells us everything we need to know about the geometry that appears at each screen pixel) and combines it with the lights to create the final image that you see. By doing this, we decouple geometry and lighting. This makes it possible to add more lights to the scene with a much smaller performance impact than in forward rendering since we don’t need to create a really complex pixel shader to handle all the lights (single-pass forward rendering) or draw the geometry over and over again for each light (multi-pass forward rendering). There are drawbacks to classic deferred rendering though. Even a minimal G-Buffer takes up quite a bit of memory and the more different types of materials you want to support, the larger the G-Buffer will need to be. Wolfgang Engel, an XNA/DirectX MVP, came up with a variation on deferred rendering which he called Light Pre-Pass Rendering. This is a three pass technique. We once again use a G-Buffer, but in this case it is smaller than the classic deferred rendering G-Buffer and can even be squeezed down to a single render target which makes it viable for graphics hardware which does not support drawing to multiple render targets at the same time. The G-Buffer is created in the first pass by rendering all the scene geometry. It only needs to store normals and the geometry’s world position. We stored the world position of the geometry at that screen position in one render target and its normal at that screen position in second render target for simplicity. The next pass draws the lights to a light accumulation buffer. The buffer starts out entirely dark and each light that is rendered adds brightness (and tint, if any) to the light buffer. These lighting calculations take into account the normal and world position of the geometry that is at each screen position, drawing the values from the G-Buffer, such that each light only affects the pixels it is supposed to have an impact on. In Maelstrom we ended up only using point lights (spheres of light that fade out as you get further from the light’s position), but you can use any kind of light you can imagine (spot lights and directional lights are the two other common light types). Adding more lights has a very low impact on rendering time and this kind of lighting tends to be much easier for the designer to work with since there’s no need for him or her to understand HLSL or even any complicated C++ in order to add, remove, reposition, or otherwise change any lights. The final pass draws the geometry a second time. This time, though, all the lighting calculations are done so all we do here is just render the meshes with their appropriate materials, adjust the color values and intensities from the material based on the light buffer value, and we’re done. Each rendering style (forward, deferred, and light pre-pass) has its own benefits and drawbacks, but in this case light pre-pass was a good solution and choosing it let us show how a state-of-the-art graphics technique works. Normal Mapping We also incorporated normal mapping. Normal mapping makes us of a special texture (a normal map) in addition to the regular texture that a material has. Normals are values used in lighting calculations to determine how much a particular light should affect a particular pixel. If you wanted to draw a brick wall, you would typically create two triangles that lined up to form a rectangle and you would apply a texture of a brick wall to them as their material. The end result of that doesn’t look very convincing though since unlike a real brick wall there are no grooves in the mortared area between each brick since our brick and mortar is just a flat texture applied to flat triangles. We could fix this by changing from two triangles to a fully modeled mesh with actual grooves, but that would add thousands of extra vertices which would lower the frame rate. So instead we use a normal map, which fakes it. One of the reasons that the two triangles + a brick wall texture approach doesn’t look right is because the lighting doesn’t behave correctly when compared to a real brick wall (or to a fully modeled mesh of a real brick wall). The normals point straight out perpendicular from the face of the rectangle whereas if we had the fully modeled mesh with actual grooves, the surface normals would only point straight out on the bricks themselves and they would curve along the mortared areas such that the lighting calculations would end up giving us the right levels of light and dark depending on the location and direction of the light. That’s where a normal map comes in. The normal map (which you can generate using a plugin for Adobe Photoshop or GIMP or by modeling a real brick wall in 3DSMax, Maya, or Blender which you then “bake” a normal map from) allows us to get the same lighting effect as we would with a fully modeled mesh while still keeping the simple two triangle + a brick wall texture approach that gives us really good performance for our game. There are limits to the effectiveness of normal mapping (you can’t use it to fake anything too deep and it doesn’t hold up as well if the camera can get really close to the object) but in Maelstrom it allowed us to keep the walls as simple triangles (like the two triangles + a brick wall texture example above) while making it seem like there were geometric grooves in the wall. Here’s a before and after screenshot using normal mapping: MaelstromNoBloomNoNormalMapping   MaelstromWithoutBloom Post-Processing Effects We also used several post-processing effects. The first was the bloom effect. Bloom is an effect that analyzes a rendered image, identifies parts that are above a certain brightness threshold, and makes those areas brighter and adds a peripheral glow to them as well, giving it a look and feel that is similar to a neon sign or to the light cycles in the movie Tron. Here’s the same shot as above with the addition of bloom: MaelstromWithNormalMapping We also made use of two different damage effects. Whenever the player took damage, we had a reddish tinge around the edge of the screen. This was simply a full screen overlay texture that is actually white but is tinted red by the shader. It is alpha-blended over the final rendered scene and fades out over the course of a couple of seconds. Rather than fading out linearly, we use a power curve which helps to sell the effect as being more complicated than it really is. Lastly we added in some damage particles. The particles themselves were created using a geometry shader. The vertex shader took in a series of points in world space and passed these points along to the geometry shader. The geometry shader expanded these points into two triangles by generating the missing vertices and applying the world-view-projection transformation matrix to transform the positions from world coordinates to homogeneous coordinates so that they can then be rasterized correctly by D3D and the resulting pixels passed along to the pixel shader. Once again we used a simple texture with alpha blending to simulate much more complicated geometry than we were actually drawing. In this case we also made use of a texture atlas (an image made up of smaller images) which, in conjunction with the randomizer we used to generate the initial vertices for the particles, allowed us to have several different particle textures. Like with the power curve for the damage texture, the texture atlas allowed us to make the particles seem more complex than they really were. It also let us show off the use of a geometry shader, a feature that was added in DirectX 10 and requires DirectX 10 or higher hardware. Audio All audio was done using the XAudio2 API.  Thankfully, we were able to get a huge head start by using some of the code from the sample project we started from.  The audio engine sets up the very basics of XAudio2, and then wraps that with a simpler API for the rest of the application to call. We don’t have many sound effects, so we on startup, we load all sounds effects and music cues into a std::map, keyed on a SoundCue enum.  Sounds are loaded using the Media Foundation classes, and the resulting byte data of the sound (and some format information) are stored in our SoundEffect class. void AudioEngine::Initialize() { m_audio = ref new Audio(); m_audio->CreateDeviceIndependentResources(); m_mediaReader = ref new MediaReader(); // Impacts m_soundMap[SoundCue::BallLaunch] = LoadSound("Sounds\\Impacts\\BallLaunch.wav"); m_soundMap[SoundCue::Buzz] = LoadSound("Sounds\\Impacts\\Buzz.wav"); m_soundMap[SoundCue::Impact1] = LoadSound("Sounds\\Impacts\\Impact1.wav"); m_soundMap[SoundCue::Impact2] = LoadSound("Sounds\\Impacts\\Impact2.wav"); ... } SoundEffect^ AudioEngine::LoadSound(String^ filename) { Array<byte>^ soundData = m_mediaReader->LoadMedia(filename); auto soundEffect = ref new SoundEffect(); soundEffect->Initialize(m_audio->SoundEffectEngine(), m_mediaReader->GetOutputWaveFormatEx(), soundData); return soundEffect; } When the game needs to play a sound, it simply calls the PlaySound method, passing in the cue to play, and the volume to play it at.  PlaySound keys into the sound map, getting the associated SoundEffect, and plays it. void AudioEngine::PlaySound(SoundCue cue, float volume, bool loop) { m_soundMap[cue]->Play(volume, loop); } MJPEG Cameras To achieve the effect of seeing the opponent in stereoscopic 3D, we strapped two Axis M1014 network cameras side-by-side.  Using Brian’s MJPEG Decoder library, with a special port to Windows Runtime, individual JPEG frames were pulled off each camera, and then applied to a texture at the back of the arena.  The image from the left camera is drawn when DirectX renders the player’s left eye, and the frame from the right camera is drawn when DirectX renders the right eye.  This is a cheap and simple way to pull off live stereoscopic 3D. void MjpegCamera::Update(GameEngine^ engine) { if(m_decoderLeft != nullptr) UpdateTexture(m_decoderLeft->CurrentFrame, &textureLeft); if(m_decoderRight != nullptr) UpdateTexture(m_decoderRight->CurrentFrame, &textureRight); Face::Update(engine); } void MjpegCamera::Render(_In_ ID3D11DeviceContext *context, _In_ ID3D11Buffer *primitiveConstantBuffer, _In_ bool isFirstPass, int eye) { if(eye == 1 && textureRight != nullptr) m_material->SetTexture(textureRight.Get()); else if(textureLeft != nullptr) m_material->SetTexture(textureLeft.Get()); GameObject::Render(context, primitiveConstantBuffer, isFirstPass); } With the distance between the cameras being about the distance of human eyes (called the intra-axial distance), the effect works pretty well! IMG_0284 Tablet/Controller The Tablet controller is the touch screen that lets the player control their 3D paddle in the Game Console app. For this part of the game system, there wasn't a reason to dive deep into DirectX and C++ since the controller is neither stereoscopic or visually intense, so we kept things simple with C#. Since the controller would also serve as our attract screen in the podium to entice potential players, we wanted to have the wait screen do something eye-catching. However, if you are moving from C# in WPF to C# and XAML in WinRT and are used to taking advantage of some of the more common "memory hoggish UX hacks" from WPF, you'll quickly find them absent in WinRT! For example, we no longer have OpacityMask, non-rectangular clipping paths or the ability to render a UIElement to a Bitmap. Our bag of UX tricks may be in need of an overhaul. However, what we do get in C# / XAML for WinRT is Z rotation, which is something we've had in Silverlight but I personally have been begging for in WPF for a long time. Therefore, the opening animation in the controller is a procedurally generated effect that rotates PNG "blades" in 3D space, creating a very compelling effect. Here is how it works. The Blade user control is a simple canvas that displays one of a few possible blade images. The Canvas has a RenderTransform to control the scale and rotation and a PlaneProjection which allows us to rotate the blade graphic in X, Y and Z space. <Canvas> <Canvas.RenderTransform> <ScaleTransform x:Name="scale" ScaleX="1.0" ScaleY="1.0" CenterX="0" CenterY="0"/> </Canvas.RenderTransform> <Canvas.Projection> <PlaneProjection x:Name="projection" CenterOfRotationX="0" CenterOfRotationY="0" CenterOfRotationZ="0" RotationX="00" RotationY="0" RotationZ="0"/> </Canvas.Projection> <Image x:Name="img0" Width="300" Height="100" Canvas.Left="-4" Canvas.Top="-12" Source="Images/s0.png"/> </Canvas> Each Blade is added dynamically to the Controller when the Tablet application first loads, stored in a List to have it's Update() method called during the CompositionTarget.Rendering() loop. protected override void OnNavigatedTo(NavigationEventArgs e) { canvas_blades.Children.Clear(); _blades.Clear(); for (int i = 0; i < NumBlades; i++) { Blade b = new Blade { X = 950.0, Y = 530.0 }; int id = _rand.Next(0, 5); b.SetBlade(id); b.Speed = .1 + id * .1; SeedBlade(b); _blades.Add(b); canvas_blades.Children.Add(b); } } void CompositionTarget_Rendering(object sender, object e) { if(_inGame) { paddle.Update(); } else if(_isClosing) { foreach (Blade b in _blades) b.UpdateExit(); } else { foreach (Blade b in _blades) b.Update(); } } Since each Blade has been assigned an individual speed and angle of rotation along all three axis, they have a very straightforward Update function. The reason we keep the rotation values between -180 and 180 during the spinning loop is to make it easier to spin them out zero when we need them to eventually leave the screen. public void Update() { _rotX += Speed; _rotZ += Speed; _rotY += Speed; if (_rotX > 180) _rotX -= 360.0; if (_rotX < -180) _rotX += 360.0; if (_rotY > 180) _rotY -= 360.0; if (_rotY < -180) _rotY += 360.0; if (_rotZ > 180) _rotZ -= 360.0; if (_rotZ < -180) _rotZ += 360.0; projection.RotationX = _rotX; projection.RotationY = _rotY; projection.RotationZ = _rotZ; } public void UpdateExit() { _rotX *= .98; _rotZ *= .98; _rotY += (90.0 - _rotY) * .1; projection.RotationX = _rotX; projection.RotationY = _rotY; projection.RotationZ = _rotZ; }   Network To continue the experiment of blending C# and C++ code, the network communication layer was written in C# as a Windows Runtime component.  Two classes are key to the system: SocketClient and SocketListener.  Player one’s game console starts a SocketListener to listen for incoming connections from each game controller, as well as player two’s game console.  Each of those use a SocketClient object to make the connection. In either case, once the connection is made, the client and the listener sit and wait for data to be transmitted.  Data must be sent as an object which implements our IGamePacket interface.  This contains two important methods: FromDataReaderAsync and WritePacket.  These methods serialize and deserialze the byte data to/from an IGameState packet of whatever type is specified in the PacketType property. namespace Coding4Fun.Maelstrom.Communication { public enum PacketType { UserInputPacket = 0, GameStatePacket } public interface IGamePacket { PacketType Type { get; } IAsyncAction FromDataReaderAsync(DataReader reader); void WritePacket(DataWriter writer); } } The controllers write UserInputPackets to the game console, consisting of X,Y positions of the paddle, as well as whether the player has tapped the screen to begin. public sealed class UserInputPacket : IGamePacket { public PacketType Type { get { return PacketType.UserInputPacket; } } public UserInputCommand Command { get; set; } public Point3 Position { get; set; } } Player one’s game console writes a GameStatePacket to player' two’s game console, which consists of the positions of each paddle, each ball, the score, and which tiles are lit for the ball splitter power up.  Player two’s Update and Render methods use this data to draw the screen appropriately. Hardware The hardware layer of this project is responsible for two big parts.  One is a rumble effect that fires every time the player is hit, and the other is a lighting effect that changes depending on the game state. As all good programmers do, we reused code from another project.  We leveraged the proven web server from Project Detroit for our Netduino, but with a few changes.  Here, we had static class “modules” which knew how to talk to the physical hardware, and “controllers” which handled items like a player scoring, game state animations, and taking damage.  Because the modules are static classes, we can have them referenced in multiple classes without issue. NETMF Web Server When a request comes in, we perform the requested operation, and then return a new line character to verify we got the request. If you don’t return any data, some clients will actually fire a second request which then can cause some odd behaviors.  The flow is as follows: 1. Parse the URL 2. Get the target controller 3. Execute the appropriate action private static void WebServerRequestReceived(Request request) { var start = DateTime.Now; Logger.WriteLine("Start: " + request.Url + " at " + DateTime.Now); try { var data = UrlHelper.ParseUrl(request.Url); var targetController = GetController(data); if (targetController != null) { targetController.ExecuteAction(data); } } catch (Exception ex0) { Logger.WriteLine(ex0.ToString()); } request.SendResponse(NewLine); Logger.WriteLine("End: " + request.Url + " at " + DateTime.Now + " took: " + (DateTime.Now - start).Milliseconds); } public static IController GetController(UrlData data) { if (data.IsDamage) return Damage; if (data.IsScore) return Score; if (data.IsGameState) return GameState; // can assume invalid return null; } Making It Shake We used a Sparkfun MP3 trigger board, a subwoofer amplifier, and bass rumble plates to create this effect.  The MP3 board requires power, and two jumpers to cause the MP3 to play.  It has an audio jack that then gets plugged into the amplifier which powers the rumble plates. From here, we just needed to wire a ground to the MP3 player’s ground pin, and the target pin on the MP3 player to a digital IO pin on the Netduino.  In the code, we declare it as an OutputPort and give it an initial state of true.  When we get a request, we toggle the pin on a separate thread. private static readonly OutputPort StopMusic = new OutputPort(Pins.GPIO_PIN_D0, true); private static readonly OutputPort Track1 = new OutputPort(Pins.GPIO_PIN_D1, true); // .. more pins public static void PlayTrack(int track) { switch (track) { case 1: TogglePin(Track1); break; // ... more cases default: // stop all, invalid choice TogglePin(StopMusic); break; } } public static void Stop() { TogglePin(StopMusic); } private static void TogglePin(OutputPort port) { var t = new Thread(() => { port.Write(false); Thread.Sleep(50); port.Write(true); }); t.Start(); } Lighting Up the Room For lighting, we used some RGB Lighting strips.  The strips can change a single color and use a PWM signal to do this.  This is different than the lighting we used in Project Detroit which allowed us to individually control each LED and used SPI to communicate.  We purchased an RGB amplifier to allow a PWM signal to power a 12 volt strip.  We purchased ours from US LED Supply and the exact product was RGB Amplifier 4A/Ch for interfacing with a Micro-Controller (PWM/TTL Input). We alter the Duty Cycle to shift the brightness of the LEDs and do this on a separate thread.  Below is a stripped down version of the lighting hardware class. public static class RgbStripLighting { private static readonly PWM RedPwm = new PWM(Pins.GPIO_PIN_D5); private static readonly PWM GreenPwm = new PWM(Pins.GPIO_PIN_D6); private static readonly PWM BluePwm = new PWM(Pins.GPIO_PIN_D9); private const int ThreadSleep = 50; private const int MaxValue = 100; const int PulsePurpleIncrement = 2; const int PulsePurpleThreadSleep = 100; private static Thread _animationThread; private static bool _killThread; #region game state animations public static void PlayGameIdle() { AbortAnimationThread(); _animationThread = new Thread(PulsePurple); _animationThread.Start(); } #endregion private static void PulsePurple() { while (!_killThread) { for (var i = 0; i <= 50; i += PulsePurpleIncrement) { SetPwmRgb(i, 0, i); } for (var i = 50; i >= 0; i -= PulsePurpleIncrement) { SetPwmRgb(i, 0, i); } Thread.Sleep(PulsePurpleThreadSleep); } } private static void AbortAnimationThread() { _killThread = true; try { if(_animationThread != null) _animationThread.Abort(); } catch (Exception ex0) { Debug.Print(ex0.ToString()); Debug.Print("Thread still alive: "); Debug.Print("Killed Thread"); } _killThread = false; } private static void SetPwmRgb(int red, int green, int blue) { // typically, 0 == off and 100 is on // things flipped however for the lighting so building this in. red = MaxValue - red; green = MaxValue - green; blue = MaxValue - blue; red = CheckBound(red, MaxValue); green = CheckBound(green, MaxValue); blue = CheckBound(blue, MaxValue); RedPwm.SetDutyCycle((uint) red); GreenPwm.SetDutyCycle((uint) green); BluePwm.SetDutyCycle((uint) blue); Thread.Sleep(ThreadSleep); } public static int CheckBound(int value, int max) { return CheckBound(value, 0, max); } public static int CheckBound(int value, int min, int max) { if (value <= min) value = min; else if (value >= max) value = max; return value; } } Conclusion We built this experience over the course of around 4 to 5 weeks.  It was our first DirectX application in a very long time, and our first C++ application in a very long time.  However, we were able to pick up the new platform and language changes fairly easily and create a simple, yet fun game in that time period. Attributions ]]> https://channel9.msdn.com/coding4fun/articles/Maelstrom-An-Overview For //build/ 2012, we wanted to showcase what Windows 8 can offer developers. There are a lot of projects showing off great things like contracts and Live Tiles, but we wanted to show off some of the lesser known features. This project focuses on one of those: stereoscopic 3D with DirectX 11.1. Prior to DirectX 11.1, stereoscopic 3D required specific hardware and a custom API written for that hardware. With DX11.1, stereoscopic 3D has been &quot;democratized.&quot; Any GPU that supports DirectX 11.1 can be connected to any device which supports stereoscopic 3D, be it a projector, an LCD TV, or anything else. Plug it in and DirectX does the rest. From the software side of things, any DX11.1 application can determine if the connected display supports stereoscopic 3D, and choose to render itself separately for the player's left and right eye. To showcase this feature, we decided to build a very simple game that would give the illusion of depth, but be easy to explain and play. What's easier than Pong? So, we built the world's most over-engineered game of 3D Pong named Maelstrom. SoftwareEach player setup consists of two applications: the DirectX 11.1 game written in C&#43;&#43;, and the touch-screen controller written in C#/XAML. Both are Windows Store applications. Since this is a two player game, there are two instances of each application running, one per player. All for applications are networked together using StreamSockets from the Windows Runtime. The two controllers and player two's DirectX game connect to player one's DirectX game, which acts as the &quot;master&quot;. Controller input is sent here, and, once the ball and paddle positions are calculated, the data is drawn for player one and sent to player two which draws the world from the other player's perspective. Direct3D ApplicationGetting Started with stereoscopic DirectX11, C&#43;&#43;, and XAMLIf you have never worked with DirectX before, it can be a little overwhelming at first. And even https://channel9.msdn.com/coding4fun/articles/Maelstrom-An-Overview Tue, 20 Nov 2012 21:00:00 GMT https://channel9.msdn.com/coding4fun/articles/Maelstrom-An-Overview Brian Peek, Clint Rutkas, Dan Fernandez, Michael B. McLaughlin, Rick Barraza Brian Peek, Clint Rutkas, Dan Fernandez, Michael B. McLaughlin, Rick Barraza 5 https://channel9.msdn.com/coding4fun/articles/Maelstrom-An-Overview/RSS 3D C++ Coding4Fun Direct 3D DirectX 11 NETMF Windows 8 Boxing Bots: An Overview Introduction In early January, we were tasked with creating a unique, interactive experience for the SXSW Interactive launch party with Frog Design. We bounced around many ideas, and finally settled on a project that Rick suggested during our first meeting: boxing robots controlled via Kinect. The theme of the opening party was Retro Gaming, so we figured creating a life size version of a classic tabletop boxing game mashed up with a "Real Steel"-inspired Kinect experience would be a perfect fit. Most importantly, since this was going to be the first big project of the new Coding4Fun team, we wanted to push ourselves to create an experience that needed each of us to bring our unique blend of hardware, software, and interaction magic to the table under an aggressively tight deadline. Hardware The BoxingBots had to be fit a few requirements: 1. They had to be fun 2. They had to survive for 4 hours, the length of the SXSW opening party 3. Each robot had to punch for 90 seconds at a time, the length of a round 4. They had to be life-size 5. They had to be Kinect-drivable 6. They had to be built, shipped, and reassembled for SXSW Creating a robot that could be beaten up for 4 hours and still work proved to be an interesting problem. After doing some research on different configurations and styles, it was decided we should leverage a prior project to get a jump start to meet the deadline. We repurposed sections of our Kinect drivable lounge chair, Jellybean! This was an advantage because it contained many known items, such as the motors, motor controllers, and chassis material.  Additionally, it was strong and fast, it was modular, and the code to drive it was already written. Jellybean would only get us part of the way there, however.  We also had to do some retrofitting to get it to work for our new project. The footprint of the base needed to shrink from 32x50 inches to 32x35 inches, while still allowing space to contain all of the original batteries, wheels, motors, motor controllers, switches, voltage adapters. We also had to change how the motors were mounted with this new layout, as well as provide for a way to easily "hot swap" the batteries out during the event. Finally, we had to mount an upper body section that looked somewhat human, complete with a head and punching arms. IMG_0087 IMG_0089 Experimenting with possible layouts The upper body had its own challenges, as it had to support a ton of equipment, including: • Punching arms • Popping head • Pneumatic valves • Air manifold • Air Tank(s) • Laptop • Phidget interface board • Phidget relay boards • Phidget LED board • Xbox wireless controller PC transmitter / receiver • Chest plate • LEDs • Sensors to detect a punch IMG_0113 Brian and Rick put together one of the upper frames Punching and Air Tanks We had to solve the problem of getting each robot to punch hard enough to register a hit on the opponent bot while not breaking the opponent bot (or itself). Bots also had to withstand a bit of side load in case the arms got tangled or took a side blow. Pneumatic actuators provided us with a lot of flexibility over hydraulics or an electrical solution since they are fast, come in tons of variations, won't break when met with resistance, and can fine tuned with a few onsite adjustments. To provide power to the actuators, the robots had two 2.5 gallon tanks pressurized to 150psi, with the actuators punching at ~70psi.  We could punch for about five 90-second rounds before needing to re-pressurize the tanks.  Pressurizing the onboard tanks was taken care of by a pair of off-the-shelf DeWalt air compressors. IMG_0134 IMG_0184IMG_0279 IMG_0172 The Head It wouldn’t be a polished game if the head didn’t pop up on the losing bot, so we added another pneumatic actuator to raise and lower the head, and some extra red and blue LEDs. This pneumatic is housed in the chest of the robot and is triggered only when the game has ended. To create the head, we first prototyped a concept with cardboard and duct tape. A rotated welding mask just happened to provide the shape we were going for on the crown, and we crafted each custom jaw with a laser cutter.  We considered using a mold and vacuum forming to create something a bit more custom, but had to scrap the idea due to time constraints. IMG_0169 IMG_0201 IMG_0268 IMG_0291 Sensors Our initial implementation for detecting punches failed due to far too many false positives. We thought using IR distance sensors would be a good solution since we could detect a “close” punch and tell the other robot to retract the arm before real contact. The test looked promising, but in practice, when the opposite sensors were close, we saw a lot of noise in the data. The backup and currently implemented solution was to install simple push switches in the chest and detect when those are clicked by the chest plate pressing against them. IMG_0200 IMG_0205 Power Different items required different voltages. The motors and pneumatic valves required 24V, the LEDs required 12V and the USB hub required 5V. We used Castle Pro BEC converters to step down the voltages. These devices are typically used in RC airplanes and helicopters. Shipping IMG_0278 IMG_0280 So how does someone ship two 700lb robots from Seattle to Austin? We did it in 8 crates. Smiley. The key thing to note is that the tops and bottoms of each robot were separated. Any wire that connected the two parts had to be able to be disconnected in some form. This affected the serial cords and the power cords (5V, 12V, 24V). Software The software and architecture went through a variety of iterations during development. The final architecture used 3 laptops, 2 desktops, an access point, and a router. It's important to note that the laptops of Robot 1 and Robot 2 are physically mounted on the backs of each Robot body, communicating through WiFi to the Admin console. The entire setup looks like the following diagram: network Admin Console The heart of the infrastructure is the Admin Console. Originally, this was also intended to be a scoreboard to show audience members the current stats of the match, but as we got further into the project, we realized this wouldn't be necessary. The robots are where the action is, and people's eyes focus there. Additionally, the robots themselves display their current health status via LEDs, so duplicating this information isn't useful. However, the admin side of this app remains. Sockets The admin console is the master controller for the game state and utilizes socket communication between it, the robots, and the user consoles. A generic socket handler was written to span each computer in the setup. The SocketListener object allows for incoming connections to be received, while the SocketClient allows clients to connect to those SocketListeners. These are generic objects, which must specify objects of type GamePacket to send and receive: public class SocketListener<TSend, TReceive> where TSend : GamePacket where TReceive : GamePacket, new()   GamePacket is a base class from which specific packets inherit: public abstract class GamePacket { public byte[] ToByteArray() { MemoryStream ms = new MemoryStream(); BinaryWriter bw = new BinaryWriter(ms); try { WritePacket(bw); } catch(IOException ex) { Debug.WriteLine("Error writing packet: " + ex); } return ms.ToArray(); } public void FromBinaryReader(BinaryReader br) { try { ReadPacket(br); } catch(IOException ex) { Debug.WriteLine("Error reading packet: " + ex); } } public abstract void WritePacket(BinaryWriter bw); public abstract void ReadPacket(BinaryReader br); } For example, in communication between the robots and the admin console, GameStatePacket and MovementDescriptorPacket are sent and received. Each GamePacket must implement its own ReadPacket and WritePacket methods to serialize itself for sending across the socket. Packets are sent between machines every "frame". We need the absolute latest game state, robot movement, etc. at all times to ensure the game is functional and responsive. image As is quite obvious, absolutely no effort was put into making the console "pretty". This is never seen by the end users and just needs to be functional. Once the robot software and the user consoles are started, the admin console initiates connections to each of those four machines. Each machine runs the SocketListener side of the socket code, while the Admin console creates four SocketClient objects to connect to each those. Once connected, the admin has control of the game and can start, stop, pause, and reset a match by sending the appropriate packets to everyone that is connected. Robot The robot UI is also never intended to be seen by an end user, and therefore contains only diagnostic information. image Each robot has a wireless Xbox 360 controller connected to it so it can be manually controlled. The UI above reflects the positions of the controller sticks and buttons. During a match, it's possible for a bot to get outside of our "safe zone". One bot might be pushing the other, or the user may be moving the bot toward the edge of the ring. To counter this, the player's coach can either temporarily move the bot, turning off Kinect input, or force the game into "referee mode" which pauses the entire match and turns off Kinect control on both sides. In either case, the robots can be driven with the controllers and reset to safe positions. Once both coaches signal that the robots are reset, the admin can then resume the match. Controlling Hardware Phidget hardware controlled our LEDs, relays, and sensors. Getting data out of a Phidget along with actions, such as opening and closing a relay, is shockingly easy as they have pretty straightforward C# APIs and samples, which is why they typically are our go-to product for projects like this. Below are some code snippets for the LEDs, relays, and sensor. LEDs – from LedController.cs This is the code that actually updates the health LEDs in the robot's chest. The LEDs were put on the board in a certain order to allow this style of iteration. We had a small issue of running out of one color of LEDs so we used some super bright ones and had to reduce the power levels to the non-super bright LEDs to prevent possible damage: private void UpdateLedsNonSuperBright(int amount, int offset, int brightness) { for (var i = offset; i < amount + offset; i++) { _phidgetLed.leds[i] = brightness / 2; } } private void UpdateLedsSuperBright(int amount, int offset, int brightness) { for (var i = offset; i < amount + offset; i++) { _phidgetLed.leds[i] = brightness; } }   Sensor data – from SensorController.cs This code snippet shows how we obtain the digital and analog inputs from the Phidget 8/8/8 interface board: public SensorController(InterfaceKit phidgetInterfaceKit) : base(phidgetInterfaceKit) { PhidgetInterfaceKit.ratiometric = true; } public int PollAnalogInput(int index) { return PhidgetInterfaceKit.sensors[index].Value; } public bool PollDigitalInput(int index) { return PhidgetInterfaceKit.inputs[index]; }   Relays – from RelayController.cs Electrical relays fire our pneumatic valves. These control the head popping and the arms punching. For our application, we wanted the ability to reset the relay automatically. When the relay is opened, an event is triggered and we create an actively polled thread to validate whether we should close the relay. The reason why we actively poll is someone could be quickly toggling the relay. We wouldn't want to close it on accident. The polling and logic does result in a possible delay or early trigger for closing the relay, but for the BoxingBots the difference of 10ms for a relay closing is acceptable: public void Open(int index, int autoCloseDelay) { UseRelay(index, true, autoCloseDelay); } public void Close(int index) { UseRelay(index, false, 0); } private void UseRelay(int index, bool openRelay, int autoCloseDelay) { AlterTimeDelay(index, autoCloseDelay); PhidgetInterfaceKit.outputs[index] = openRelay; } void _relayController_OutputChange(object sender, OutputChangeEventArgs e) { // closed if (!e.Value) return; ThreadPool.QueueUserWorkItem(state => { if (_timeDelays.ContainsKey(e.Index)) { while (_timeDelays[e.Index] > 0) { Thread.Sleep(ThreadTick); _timeDelays[e.Index] -= ThreadTick; } } Close(e.Index); }); } public int GetTimeDelay(int index) { if (!_timeDelays.ContainsKey(index)) return 0; return _timeDelays[index]; } public void AlterTimeDelay(int index, int autoCloseDelay) { _timeDelays[index] = autoCloseDelay; }   User Console   IMG_0297 Since the theme of the party was Retro Gaming, we wanted to go for an early 80's Sci-fi style interface, complete with starscape background and solar flares! We wanted to create actual interactive elements, though, to maintain the green phosphor look of early monochrome monitors. Unlike traditional video games, however, the screens are designed not as the primary focus of attention, but rather to help calibrate the player before the round and provide secondary display data during the match. The player should primarily stay focused on the boxer during the match, so the interface is designed to sit under the players view line and serve as more of a dashboard during each match. However, during calibration before each round, it is important to have the player understand how their core body will be used to drive the Robot base during each round. To do this, we needed to track an average of the joints that make up each fighter's body core. We handled the process by creating a list of core joints and a variable that normalizes the metric distances returned from the Kinect sensor into a human-acceptable range of motion: private static List<JointType> coreJoints = newList<JointType>( newJointType[] { JointType.AnkleLeft, JointType.AnkleRight, JointType.ShoulderCenter, JointType.HipCenter }); private const double RangeNormalizer = .22; private const double NoiseClip = .05; And then during each skeleton calculation called by the game loop, we average the core positions to determine the averages of the players as they relate to their playable ring boundary: public staticMovementDescriptorPacket AnalyzeSkeleton(Skeleton skeleton) { // ... CoreAverageDelta.X = 0.0; CoreAverageDelta.Z = 0.0; foreach (JointType jt in CoreJoints) { CoreAverageDelta.X += skeleton.Joints[jt].Position.X - RingCenter.X; CoreAverageDelta.Z += skeleton.Joints[jt].Position.Z - RingCenter.Z; } CoreAverageDelta.X /= CoreJoints.Count * RangeNormalizer; CoreAverageDelta.Z /= CoreJoints.Count * RangeNormalizer; // ... if (CoreAverageDelta.Z > NoiseClip || CoreAverageDelta.Z < -NoiseClip) { packet.Move = -CoreAverageDelta.Z; } if (CoreAverageDelta.X > NoiseClip || CoreAverageDelta.X < -NoiseClip) { packet.Strafe = CoreAverageDelta.X; } } In this way, we filter out insignificant data noise and allow the player's average core body to serve as a joystick for driving the robot around. Allowing them to lean at any angle, the move and strafe values are accordingly set to allow for a full 360 degrees of movement freedom, while at the same time not allowing any one joint to unevenly influence their direction of motion. Another snippet of code that may be of interest is the WPF3D rendering we used to visualize the skeleton. Since the Kinect returns joint data based off of a center point, it is relatively easy to wire up a working 3D model in WPF3D off of the skeleton data, and we do this in the ringAvatar.xaml control. In the XAML, we simply need a basic Viewport3D with camera, lights, and an empty ModelVisual3D container to hold or squares. The empty container looks like this:               <ModelVisual3D x:Name="viewportModelsContainer2"> <ModelVisual3D.Transform> <Transform3DGroup> <RotateTransform3D x:Name="bodyRotationCenter" CenterX="0" CenterY="0" CenterZ="0"> <RotateTransform3D.Rotation> <AxisAngleRotation3D x:Name="myAngleRotation" Axis="0,1,0" Angle="-40"/> </RotateTransform3D.Rotation> </RotateTransform3D> </Transform3DGroup> </ModelVisual3D.Transform> </ModelVisual3D> In the code, we created a generic WPF3DModel that inherits from UIElement3D and is used to store the basic positioning properties of each square. In the constructor of the object, though, we can pass a reference key to a XAML file that defines the 3D mesh to use: public WPF3DModel(string resourceKey) { this.Visual3DModel = Application.Current.Resources[resourceKey] as Model3DGroup; } This is a handy trick when you need to do a fast WPF3D demo and require a certain level of flexibility. To create a 3D cube for each joint when ringAvatar is initialized, we simply do this: private readonly List<WPF3DModel> _models = new List<WPF3DModel>(); private void CreateViewportModels() { for (int i = 0; i < 20; i++) { WPF3DModel model = new WPF3DModel("mesh_cube"); viewportModelsContainer2.Children.Add(model); // ... _models.Add(model); } // ... } And then each time we need to redraw the skeleton, we loop through the skeleton data and set the cube position like so: if (SkeletonProcessor.RawSkeleton.TrackingState == SkeletonTrackingState.Tracked) { int i = 0; foreach (Joint joint in SkeletonProcessor.RawSkeleton.Joints) { if (joint.TrackingState == JointTrackingState.Tracked) { _models[i].Translate( joint.Position.X * 8.0, joint.Position.Y * 10.0, joint.Position.Z * -10.0); i++; } } // ... } There are a few other areas in the User Console that you may want to further dig into, including the weighting for handling a punch as well dynamically generating arcs based on the position of the fist to the shoulder. However, for this experience, the User Console serves as a secondary display to support the playing experience and gives both the player and audience a visual anchor for the game. Making a 700lb Tank Drive like a First Person Shooter The character in a first person shooter (FPS) video game has an X position, a Y position, and a rotation vector. On an Xbox controller, the left stick controls the X,Y position. Y is the throttle (forward and backward), X is the strafing amount (left and right), and the right thumb stick moves the camera to change what you're looking at (rotation).  When all three are combined, the character can do things such as run around someone while looking at them. In the prior project, we had existing code that worked for controlling all 4 motors at the same time, working much like a tank does, so we only had throttle (forward and back) and strafing (left and right). Accordingly, we can move the motors in all directions, but there are still scenarios in which the wheels fight one another and the base won't move. By moving to a FPS style, we eliminate the ability to move the wheels in an non-productive way and actually make it a lot easier to drive. Note that Clint had some wiring "quirks" with polarity and which motor was left VS right, he had to correct in these quirks in software Smiley: public Speed CalculateSpeed(double throttleVector, double strafeVector, double rotationAngle) { rotationAngle = VerifyLegalValues(rotationAngle); rotationAngle = AdjustValueForDeadzone(rotationAngle, AllowedRotationAngle, _negatedAllowedRotationAngle); // flipped wiring, easy fix is here throttleVector *= -1; rotationAngle *= -1; // miss wired, had to flip throttle and straff for calc return CalculateSpeed(strafeVector + rotationAngle, throttleVector, strafeVector - rotationAngle, throttleVector); } protected Speed CalculateSpeed(double leftSideThrottle, double leftSideVectorMultiplier, double rightSideThrottle, double rightSideVectorMultiplier) { /* code from Jellybean */ } Conclusion The Boxing Bots project was one of the biggest things we have built to date. It was also one of our most successful projects. Though it was a rainy, cold day and night in Austin when the bots were revealed, and we had to move locations several times during setup to ensure the bots and computers wouldn't be fried by the rain, they ran flawlessly for the entire event and contestants seemed to have a lot of fun driving them. IMG_0302 ]]> https://channel9.msdn.com/coding4fun/articles/Boxing-Bots-An-Overview IntroductionIn early January, we were tasked with creating a unique, interactive experience for the SXSW Interactive launch party with Frog Design. We bounced around many ideas, and finally settled on a project that Rick suggested during our first meeting: boxing robots controlled via Kinect. The theme of the opening party was Retro Gaming, so we figured creating a life size version of a classic tabletop boxing game mashed up with a &quot;Real Steel&quot;-inspired Kinect experience would be a perfect fit. Most importantly, since this was going to be the first big project of the new Coding4Fun team, we wanted to push ourselves to create an experience that needed each of us to bring our unique blend of hardware, software, and interaction magic to the table under an aggressively tight deadline. HardwareThe BoxingBots had to be fit a few requirements: They had to be fun They had to survive for 4 hours, the length of the SXSW opening party Each robot had to punch for 90 seconds at a time, the length of a round They had to be life-size They had to be Kinect-drivable They had to be built, shipped, and reassembled for SXSW Creating a robot that could be beaten up for 4 hours and still work proved to be an interesting problem. After doing some research on different configurations and styles, it was decided we should leverage a prior project to get a jump start to meet the deadline. We repurposed sections of our Kinect drivable lounge chair, Jellybean! This was an advantage because it contained many known items, such as the motors, motor controllers, and chassis material. Additionally, it was strong and fast, it was modular, and the code to drive it was already written. Jellybean would only get us part of the way there, however. We also had to do some retrofitting to get it to work for our new project. The footprint of the base needed to shrink from 32x50 inches to 32x35 inches, while still allowing space to contain all of the original batteries, wheels, motors, motor contr https://channel9.msdn.com/coding4fun/articles/Boxing-Bots-An-Overview Thu, 04 Oct 2012 21:00:00 GMT https://channel9.msdn.com/coding4fun/articles/Boxing-Bots-An-Overview Brian Peek, Clint Rutkas, Dan Fernandez, Rick Barraza Brian Peek, Clint Rutkas, Dan Fernandez, Rick Barraza 10 https://channel9.msdn.com/coding4fun/articles/Boxing-Bots-An-Overview/RSS Hardware Kinect WPF Phidgets The HP Printer Display Hack (with financial goodness) The HP Printer Display Hack is a simple background application that periodically checks the current price of a selected stock and sends it to the display of HP (and compatible) laser printers. Introduction This app is based on an old hack from back to at least 1997 that uses the HP Job control language to change the text on the LCD status display. Some background on this hack can be found here: http://www.irongeek.com/i.php?page=security/networkprinterhacking. There are various versions of the hack code out there, and typically they all work the same way: you specify the address of the printer and the message to send, open a TCP connection to the printer over port 9100, and then send a command to update the display. This app is a variation of that hack. It’s a tray application that periodically checks the stock price for a company and then sends a formatted message of the stock symbol and price to a specified printer. To get the current stock price, we retrieve the data from Yahoo! through finance.yahoo.com. The data comes back in CSV format. To save a step in parsing the CSV columns, we use YQL, the Yahoo! Query Language. Yahoo! created YQL to provide a SQL-like API for querying data from various online web services. YQL! can return XML or JSON data, and we’ll take the XML and use LINQ to parse the data. 2012-08-27_12-19-35_454 How to Use the App The first time you run the app, the main form will appear and you'll be able to enter in the stock symbol and the IP address of your printer. Click the “Get Printer” button to view a dialog listing the available printers connected on port 9100. There are two checkboxes. The first one is labeled “Start with Windows”. When this setting is saved, the following code is executed to tell Windows whether to start the app when user logs in: C# private void StartWithWindows(bool start) { using (RegistryKey hkcu = Registry.CurrentUser) { using (RegistryKey runKey = hkcu.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true)) { if (runKey == null) return; if (start) runKey.SetValue(wpfapp.Properties.Resources.Code4FunStockPrinter, Assembly.GetEntryAssembly().Location); else { if (runKey.GetValue(wpfapp.Properties.Resources.Code4FunStockPrinter) != null) runKey.DeleteValue(wpfapp.Properties.Resources.Code4FunStockPrinter); } } } } VB Private Sub StartWithWindows(ByVal start As Boolean) Using hkcu As RegistryKey = Registry.CurrentUser Using runKey As RegistryKey = hkcu.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", True) If runKey Is Nothing Then Return End If If start Then runKey.SetValue(My.Resources.Code4FunStockPrinter, System.Reflection.Assembly.GetEntryAssembly().Location) Else If runKey.GetValue(My.Resources.Code4FunStockPrinter) IsNot Nothing Then runKey.DeleteValue(My.Resources.Code4FunStockPrinter) End If End If End Using End Using End Sub The enabled checkbox is used so that you can pause the sending of the stock price to the printer without having to exit the app. When you press the “Start” button, you are prompted to save any changed settings and the app hides the main form, leaving just the system tray icon. While the app is running, it will check the stock price every 5 minutes. If the price has changed, it tells the printer to display the stock symbol and price on the display. A DispatcherTimer object is used to determine when to check the stock price. It’s created when the main form is created and will only execute the update code when the settings have been defined and enabled. If an unexpected error occurs, the DispatcherUnhandledException event handler will log the error to a file and alert the user: C# void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) { // stop the timer _mainWindow.StopPrinterHacking(); // display the error _mainWindow.LogText("Sending the stock prince to the printer was halted due to this error:" + e.Exception.ToString()); // display the form ShowMainForm(); // Log the error to a file and notify the user Exception theException = e.Exception; string theErrorPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\PrinterDisplayHackError.txt"; using (System.IO.TextWriter theTextWriter = new System.IO.StreamWriter(theErrorPath, true)) { DateTime theNow = DateTime.Now; theTextWriter.WriteLine(String.Format("The error time: {0} {1}", theNow.ToShortDateString(), theNow.ToShortTimeString())); while (theException != null) { theTextWriter.WriteLine("Exception: " + theException.ToString()); theException = theException.InnerException; } } MessageBox.Show("An unexpected error occurred. A stack trace can be found at:\n" + theErrorPath); e.Handled = true; } VB Private Sub App_DispatcherUnhandledException(ByVal sender As Object, ByVal e As System.Windows.Threading.DispatcherUnhandledExceptionEventArgs) ' stop the timer _mainWindow.StopPrinterHacking() ' display the error _mainWindow.LogText("Sending the stock prince to the printer was halted due to this error:" & e.Exception.ToString()) ' display the form ShowMainForm() ' Log the error to a file and notify the user Dim theException As Exception = e.Exception Dim theErrorPath As String = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) & "\PrinterDisplayHackError.txt" Using theTextWriter As System.IO.TextWriter = New System.IO.StreamWriter(theErrorPath, True) Dim theNow As Date = Date.Now theTextWriter.WriteLine(String.Format("The error time: {0} {1}", theNow.ToShortDateString(), theNow.ToShortTimeString())) Do While theException IsNot Nothing theTextWriter.WriteLine("Exception: " & theException.ToString()) theException = theException.InnerException Loop End Using MessageBox.Show("An unexpected error occurred. A stack trace can be found at:" & vbLf & theErrorPath) e.Handled = True End Sub   The User Interface The application currently looks like this: image Pressing the “Get Printer” button opens a dialog that looks like this: image The UI was designed with WPF and uses the basic edit controls as well as a theme from the WPF Themes project on CodePlex. On the main form, the stock symbol, printer IP address, and the check boxes using data bindings to bind each control to a custom setting are defined in the PrinterHackSettings class. The settings are defined in a class descended from ApplicationSettingsBase. The .NET runtime will read and write the settings based on the rules defined here. The big RichTextBog in the center of the form is used to display the last 10 stock price updates. The app keeps a queue of the stock price updates, and when the queue is updated it’s sent to the RichTextBox with the following code: C# public void UpdateLog(RichTextBox rtb) { int i = 0; TextRange textRange = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd); textRange.Text = string.Empty; foreach (var lg in logs) { i++; TextRange tr = new TextRange(rtb.Document.ContentEnd, rtb.Document.ContentEnd) { Text = String.Format("{0} : ", lg.LogTime.ToString("hh:mm:ss")) }; tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.DarkRed); tr = new TextRange(rtb.Document.ContentEnd, rtb.Document.ContentEnd) { Text = lg.LogMessage + Environment.NewLine }; tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Black); } if (i > 10) logs.Dequeue(); rtb.ScrollToEnd(); }   VB Public Sub UpdateLog(ByVal rtb As RichTextBox) Dim i As Integer = 0 For Each lg As LogEntry In logs i += 1 Dim tr As New TextRange(rtb.Document.ContentEnd, rtb.Document.ContentEnd) With {.Text = String.Format("{0} : ", lg.LogTime.ToString("hh:mm:ss"))} tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red) tr = New TextRange(rtb.Document.ContentEnd, rtb.Document.ContentEnd) With {.Text = lg.LogMessage & Environment.NewLine} tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.White) Next lg If i > 10 Then logs.Dequeue() End If rtb.ScrollToEnd() End Sub Displaying a notification trace icon WPF does not provide any functionality for running an app with just an icon in the notification area of the taskbar. We need to tap into some WinForms functionality. Add a reference to the System.Windows.Form namespace to the project. In the App.xaml file, add an event handler to the Startup event. Visual Studio will wire up an Application.Startup event in the code behind file. We can use that event to add a WinForms.NotifyIcon and wireup a context menu to it: C# private void Application_Startup(object sender, StartupEventArgs e) { _notifyIcon = new WinForms.NotifyIcon(); _notifyIcon.DoubleClick += notifyIcon_DoubleClick; _notifyIcon.Icon = wpfapp.Properties.Resources.Icon; _notifyIcon.Visible = true; WinForms.MenuItem[] items = new[] { new WinForms.MenuItem("&Settings", Settings_Click) { DefaultItem = true } , new WinForms.MenuItem("-"), new WinForms.MenuItem("&Exit", Exit_Click) }; _notifyIcon.ContextMenu = new WinForms.ContextMenu(items); _mainWindow = new MainWindow(); if (!_mainWindow.SettingsAreValid()) _mainWindow.Show(); else _mainWindow.StartPrinterHacking(); } VB Private Sub Application_Startup(ByVal sender As Object, ByVal e As StartupEventArgs) _notifyIcon = New System.Windows.Forms.NotifyIcon() AddHandler _notifyIcon.DoubleClick, AddressOf notifyIcon_DoubleClick _notifyIcon.Icon = My.Resources.Icon _notifyIcon.Visible = True Dim items() As System.Windows.Forms.MenuItem = {New System.Windows.Forms.MenuItem("&Settings", AddressOf Settings_Click) With {.DefaultItem = True}, New System.Windows.Forms.MenuItem("-"), New System.Windows.Forms.MenuItem("&Exit", AddressOf Exit_Click)} _notifyIcon.ContextMenu = New System.Windows.Forms.ContextMenu(items) _mainWindow = New MainWindow() If Not _mainWindow.SettingsAreValid() Then _mainWindow.Show() Else _mainWindow.StartPrinterHacking() End If End Sub   Getting the Stock Information From the Yahoo Financial site, you get can download a CSV file for any specified stock. Here's a web site that documents the format needed to get the right fields: http://www.gummy-stuff.org/Yahoo-data.htm. We want to return the stock symbol and the last traded price. That works out to be “s” and “l1”, respectively. If you open the following URL with a browser, a file named quotes.csv will be returned: http://download.finance.yahoo.com/d/quotes.csv?s=MSFT&f=sl1 You should get a file like this: quotes_csv The first field is the stock symbol and the second is the last recorded price. You could just read that data and parse out the fields, but we can get the data in more readable format. Yahoo! has a tool called the YQL Console that will you let you interactively query against Yahoo! and other web service providers. While it's overkill to use on a two column CSV file, it can be used to tie together data from multiple services. To use our MSFT stock query with YQL, we format the query like this: select * from csv where url='http://download.finance.yahoo.com/d/quotes.csv?s=MSFT&f=sl1' and columns='symbol,price' You can see this query loaded into the YQL Console here. yql When you click the “TEST” button, the YQL query is executed and the results displayed in the lower panel. By default, the results are in XML, but you can also get the data back in JSON format. Our result set has been transformed into the following XML: <?xml version="1.0" encoding="UTF-8"?> <query xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" yahoo:count="1" yahoo:created="2012-08-23T02:36:06Z" yahoo:lang="en-US"> <results> <row> <symbol>MSFT</symbol> <price>30.54</price> </row> </results> </query>   This XML document can be easily parsed in the application code. The URL listed below “THE REST QUERY” on the YQL page is the YQL query encoded so that it can be sent as a GET request. For this YQL query, we use the following URL: http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes.csv%3Fs%3DMSFT%26f%3Dsl1'%20and%20columns%3D'symbol%2Cprice' This is the URL that our application uses to get the stock price. Notice the MSFT in bold face—we replace that hard coded stock symbol with a format item and just use String.Format() to generate the URL at run time. To get the stock price from our code, we can wrap this with the following method: C# public string GetPriceFromYahoo(string tickerSymbol) { string price = string.Empty; string url = string.Format("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes.csv%3Fs%3D{0}%26f%3Dsl1'%20and%20columns%3D'symbol%2Cprice'", tickerSymbol); try { Uri uri = new Uri(url); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri); HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); XDocument doc = XDocument.Load(resp.GetResponseStream()); resp.Close(); var ticker = from query in doc.Descendants("query") from results in query.Descendants("results") from row in query.Descendants("row") select new { price = row.Element("price").Value }; price = ticker.First().price; } catch (Exception ex) { price = "Exception retrieving symbol: " + ex.Message; } return price; } VB Public Function GetPriceFromYahoo(ByVal tickerSymbol As String) As String Dim price As String Dim url As String = String.Format("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes.csv%3Fs%3D{0}%26f%3Dsl1'%20and%20columns%3D'symbol%2Cprice'", tickerSymbol) Try Dim uri As New Uri(url) Dim req As HttpWebRequest = CType(WebRequest.Create(uri), HttpWebRequest) Dim resp As HttpWebResponse = CType(req.GetResponse(), HttpWebResponse) Dim doc As XDocument = XDocument.Load(resp.GetResponseStream()) resp.Close() Dim ticker = From query In doc.Descendants("query") , results In query.Descendants("results") , row In query.Descendants("row") _ Let xElement = row.Element("price") _ Where xElement IsNot Nothing _ Select New With {Key .price = xElement.Value} price = ticker.First().price Catch ex As Exception price = "Exception retrieving symbol: " & ex.Message End Try Return price End Function   While this code makes the readying of a two column CSV file more complicated than it needs to be, it makes it easier to adapt this code to read the results for multiple stock symbols and/or additional fields. Getting the List of Printers We are targeting a specific type of printer: those that use the HP PJL command set. Since we talk to these printers over port 9100, we only need to list the printers that listen on that port. We can use Windows Management Instrumentation (WMI) to list the printer TCP/IP addresses that are using port 9100.  The WMI class Win32_TCPIPPrinterPort can be used for that purpose, and we’ll use the following WMI query: Select Name, HostAddress from Win32_TCPIPPrinterPort where PortNumber = 9100 This returns the list of port names and addresses on your computer that are being used over port 9100. Take that list and store it in a dictionary for a quick lookup: C# static public Dictionary<string, IPAddress> GetPrinterPorts() { var ports = new Dictionary<string, IPAddress>(); ObjectQuery oquery = new ObjectQuery("Select Name, HostAddress from Win32_TCPIPPrinterPort where PortNumber = 9100"); ManagementObjectSearcher mosearcher = new ManagementObjectSearcher(oquery); using (var searcher = new ManagementObjectSearcher(oquery)) { var objectCollection = searcher.Get(); foreach (ManagementObject managementObjectCollection in objectCollection) { var portAddress = IPAddress.Parse(managementObjectCollection.GetPropertyValue("HostAddress").ToString()); ports.Add(managementObjectCollection.GetPropertyValue("Name").ToString(), portAddress); } } return ports; } VB Public Shared Function GetPrinterPorts() As Dictionary(Of String, IPAddress) Dim ports = New Dictionary(Of String, IPAddress)() Dim oquery As New ObjectQuery("Select Name, HostAddress from Win32_TCPIPPrinterPort where PortNumber = 9100") Dim mosearcher As New ManagementObjectSearcher(oquery) Using searcher = New ManagementObjectSearcher(oquery) Dim objectCollection = searcher.Get() For Each managementObjectCollection As ManagementObject In objectCollection Dim portAddress = IPAddress.Parse(managementObjectCollection.GetPropertyValue("HostAddress").ToString()) ports.Add(managementObjectCollection.GetPropertyValue("Name").ToString(), portAddress) Next managementObjectCollection End Using Return ports End Function   Next, we get the list of printers that this computer knows about. We could do that through WMI, but I decided to stay closer to the .NET Framework and use the LocalPrintServer class. The GetPrintQueues method returns a collection of print queues of the type PrintQueueCollection. We can then iterate through the PrintQueueCollection and look for all printers that have a port name that matches the names returned by the WMI query. That gives code that looks like this: C# public class LocalPrinter { public string Name { get; set; } public string PortName { get; set; } public IPAddress Address { get; set; } } static public List<LocalPrinter> GetPrinters() { Dictionary<string, IPAddress> ports = GetPrinterPorts(); EnumeratedPrintQueueTypes[] enumerationFlags = { EnumeratedPrintQueueTypes.Local }; LocalPrintServer printServer = new LocalPrintServer(); PrintQueueCollection printQueuesOnLocalServer = printServer.GetPrintQueues(enumerationFlags); return (from printer in printQueuesOnLocalServer where ports.ContainsKey(printer.QueuePort.Name) select new LocalPrinter() { Name = printer.Name, PortName = printer.QueuePort.Name, Address = ports[printer.QueuePort.Name] }).ToList(); }   VB Public Class LocalPrinter Public Property Name() As String Public Property PortName() As String Public Property Address() As IPAddress End Class Public Shared Function GetPrinters() As List(Of LocalPrinter) Dim ports As Dictionary(Of String, IPAddress) = GetPrinterPorts() Dim enumerationFlags() As EnumeratedPrintQueueTypes = { EnumeratedPrintQueueTypes.Local } Dim printServer As New LocalPrintServer() Dim printQueuesOnLocalServer As PrintQueueCollection = printServer.GetPrintQueues(enumerationFlags) Return ( _ From printer In printQueuesOnLocalServer _ Where ports.ContainsKey(printer.QueuePort.Name) _ Select New LocalPrinter() With {.Name = printer.Name, .PortName = printer.QueuePort.Name, .Address = ports(printer.QueuePort.Name)}).ToList() End Function Sending the Stock Price to the Printer The way to send a message to a HP display is via a PJL command. PJL stands for Printer Job Language. Not all PJL commands are recognized by every HP printer, but if you have an HP laser printer with a display, the command should work. This should work for any printer that is compatible with HP’s PJL command set. For the common PJL commands, HP has an online document here. We will be using the “Ready message display” PJL command. All PJL commands will start and end with a sequence of bytes called the “Universal Exit Language” or UEL. This sequence tells the printer that it’s about to receive a PJL command. The UEL is defined as <ESC>%-12345X The format of the packet sent to the printer is be "UEL PJL command UEL". The Ready message display format is @PJL RDYMSG DISPLAY=”message”[<CR>]<LF> To send the command that has the printer display “Hello World”, you would send the following sequence: <ESC>%-12345X@PJL RDYMSG DISPLAY=”Hello World”[<CR>]<LF><ESC>%-12345X[<CR>]<LF> We wrap this up in a class called SendToPrinter and the good stuff gets executed in the Send method, as listed below: C# public class SendToPrinter { public string host { get; set; } public int Send(string message) { IPAddress addr = null; IPEndPoint endPoint = null; try { addr = Dns.GetHostAddresses(host)[0]; endPoint = new IPEndPoint(addr, 9100); } catch (Exception e) { return 1; } Socket sock = null; String head = "\u001B%-12345X@PJL RDYMSG DISPLAY = \""; String tail = "\"\r\n\u001B%-12345X\r\n"; ASCIIEncoding encoding = new ASCIIEncoding(); try { sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); sock.Connect(endPoint); sock.Send(encoding.GetBytes(head)); sock.Send(encoding.GetBytes(message)); sock.Send(encoding.GetBytes(tail)); sock.Close(); } catch (Exception e) { return 1; } int bytes = (head + message + tail).Length; return 0; } } VB Public Function Send(ByVal message As String) As Integer Dim endPoint As IPEndPoint = Nothing Try Dim addr As IPAddress = Dns.GetHostAddresses(Host)(0) endPoint = New IPEndPoint(addr, 9100) Catch Return 1 End Try Dim startPJLSequence As String = ChrW(&H1B).ToString() & "%-12345X@PJL RDYMSG DISPLAY = """ Dim endPJLSequence As String = """" & vbCrLf & ChrW(&H1B).ToString() & "%-12345X" & vbCrLf Dim encoding As New ASCIIEncoding() Try Dim sock As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP) sock.Connect(endPoint) sock.Send(encoding.GetBytes(startPJLSequence)) sock.Send(encoding.GetBytes(message)) sock.Send(encoding.GetBytes(endPJLSequence)) sock.Close() Catch Return 1 End Try Return 0 End Function   The Installer The installer for this app was written with WiX, Windows Installer XML. WiX is an open source project created by Rob Mensching that lets you build Windows Installer .msi and .msm files from XML source code. I used the release candidate of WiX 3.6, but any recent version should work. Of course, you don’t need an installer if you build the app yourself. Setting InstalScope to “perUser” designates this package as being a per-user install. Adding the property “WixAppFolder” and set to “WixPerUserFolder” tells WiX to install this app under %LOCALAPPDATA% instead of under %ProgramFiles%. This eliminates the need for the installer to request elevated rights and the UAC prompt: <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"> <Product Id="*" Name="Coding4Fun Printer Display Hack" Language="1033" Version="1.0.0.0" Manufacturer="Coding4Fun" UpgradeCode="e0a3eed3-b61f-46da-9bda-0d546d2a0622"> <Package InstallerVersion="200" Compressed="yes" InstallScope="perUser" /> <Property Id="WixAppFolder" Value="WixPerUserFolder" /> Because we are not touching any system settings, I eliminated the creation of a system restore point at the start of the installation process. This greatly speeds up the installation of the app, and is handled by adding a property named MSIFASTINSTALL with the value of “1”: <Property Id="MSIFASTINSTALL" Value="1" /> I modified the UI sequence to skip over the end user license agreement. There is nothing to license here and no one reads EULAs anyways. To do this, I needed to download the WiX source code and extract a file named WixUI_Mondo.wxs. I added it to the installer project and renamed it to WixUI_MondoNoLicense.wxs. I also added a checkbox to the exit dialog to allow the user to launch the app after it been installed: <Property Id="WIXUI_EXITDIALOGOPTIONALCHECKBOXTEXT" Value="Launch Printer Display Hack" /> <Property Id="WixShellExecTarget" Value="[#exe]" /> <CustomAction Id="LaunchApplication" BinaryKey="WixCA" DllEntry="WixShellExec" Impersonate="yes" /> <UI> <UIRef Id="WixUI_MondoNoLicense"/> <Publish Dialog="ExitDialog" Control="Finish" Event="DoAction" Value="LaunchApplication"> WIXUI_EXITDIALOGOPTIONALCHECKBOX = 1 and NOT Installed </Publish> </UI>   When you build the installer, it generates two ICE91 warning messages. An ICE91 warning occurs when you install a file or shortcut into a per-user only folder. Since we have explicitly set the InstallScope to “perUser”, we can safely ignore these two warnings. If you hate warning messages, you can use the tool settings for the installer project to suppress ICE91 validation checks: toolsettings Conclusion I have had various versions of this app running in my office for over a year. It’s been set to show our current stock price on the main printer in the development department. It’s fun to watch people walk near the printer just to check out the current stock price. If you want to try this out, the download link for the source code and installer is at the top of the article! About The Author I am a senior R&D engineer for Tyler Technologies, working on our next generation of school bus routing software. I also am the leader of the Tech Valley .NET Users Group (TVUG). You can follow me at @anotherlab and check out my blog at anotherlab.rajapet.net. I would list my G+ address, but I don’t use it. I started out with a VIC-20 and been slowly moving up the CPU food chain ever since. I would like to thank Brian Peek on the Coding4Fun team for his encouragement and suggestions and for letting me steal large chunks of the UI code from his TweeVo project . ]]> https://channel9.msdn.com/coding4fun/articles/The-HP-Printer-Display-Hack-with-financial-goodness The HP Printer Display Hack is a simple background application that periodically checks the current price of a selected stock and sends it to the display of HP (and compatible) laser printers. IntroductionThis app is based on an old hack from back to at least 1997 that uses the HP Job control language to change the text on the LCD status display. Some background on this hack can be found here: http://www.irongeek.com/i.php?page=security/networkprinterhacking. There are various versions of the hack code out there, and typically they all work the same way: you specify the address of the printer and the message to send, open a TCP connection to the printer over port 9100, and then send a command to update the display. This app is a variation of that hack. It’s a tray application that periodically checks the stock price for a company and then sends a formatted message of the stock symbol and price to a specified printer. To get the current stock price, we retrieve the data from Yahoo! through finance.yahoo.com. The data comes back in CSV format. To save a step in parsing the CSV columns, we use YQL, the Yahoo! Query Language. Yahoo! created YQL to provide a SQL-like API for querying data from various online web services. YQL! can return XML or JSON data, and we’ll take the XML and use LINQ to parse the data. How to Use the AppThe first time you run the app, the main form will appear and you'll be able to enter in the stock symbol and the IP address of your printer. Click the “Get Printer” button to view a dialog listing the available printers connected on port 9100. There are two checkboxes. The first one is labeled “Start with Windows”. When this setting is saved, the following code is executed to tell Windows whether to start the app when user logs in: C# private void StartWithWindows(bool start) { using (RegistryKey hkcu = Registry.CurrentUser) { using (RegistryKey runKey = hkcu.OpenSubKey(@&quot;Software\Microsoft\Windows\CurrentVersion\Run https://channel9.msdn.com/coding4fun/articles/The-HP-Printer-Display-Hack-with-financial-goodness Thu, 13 Sep 2012 17:00:00 GMT https://channel9.msdn.com/coding4fun/articles/The-HP-Printer-Display-Hack-with-financial-goodness Chris Miller Chris Miller 2 https://channel9.msdn.com/coding4fun/articles/The-HP-Printer-Display-Hack-with-financial-goodness/RSS WiX WPF Printers Using the Adafruit Arduino Logger Shield on a Netduino C9 Netduino Shield Series - Using Arduino Shields with a Netduino - Part II Introduction In our previous article, we examined what an Arduino shield is, how to build a simple custom shield and discussed how to quickly identify shields that are good candidates for a Netduino adaptation versus shields that may not be. In this article, we’ll take a popular Arduino Logger Shield produced by Adafruit and we’ll interface it with a Netduino / Plus microcontroller image The Arduino Logger Shield is an excellent one to start with because it offers immediate benefits to a Netduino / Plus user: • Time-keeping • SD card storage • Two user-controllable LEDs • A small prototyping area • An onboard 3.3v voltage regulator for clean analog readings and power decoupling In our C# data logging application, we'll interact with the time keeper, the SD card storage and its 'card detect' pin, the two LEDs as well as a temperature sensor (not included with the shield). Before diving into the details associated with the hardware, you may want to take a look at the C# objects representing the hardware: public static readonly string SdMountPoint = "SD"; public static OutputPort LedRed = new OutputPort(Pins.GPIO_PIN_D0, false); public static OutputPort LedGreen = new OutputPort(Pins.GPIO_PIN_D1, false); public static InputPort CardDetect = new InputPort(Pins.GPIO_PIN_D3, true, Port.ResistorMode.PullUp); public static readonly Cpu.Pin ThermoCoupleChipSelect = Pins.GPIO_PIN_D2; public static DS1307 Clock; public static Max6675 ThermoCouple; and their initialization: public static void InitializePeripherals() { LedGreen.Write(true); Clock = new DS1307(); ThermoCouple = new Max6675(); InitializeStorage(true); InitializeClock(new DateTime(2012, 06, 14, 17, 00, 00)); ThermoCouple.Initialize(ThermoCoupleChipSelect); TemperatureSampler = new Timer(new TimerCallback(LogTemperature), null, 250, TemperatureLoggerPeriod); LedGreen.Write(false); } The SD card, represented by the SdMountPoint string, communicates with the application over SPI. The presence of the SD card in the reader is determined through the CardDetect input pin. The LEDs are simple outputs that we'll turn ON / OFF as the peripherals gets initialized and file I/Os take place with the SD card. The clock communicates with the application over the I2C protocol. The clock's most important functions are accessed through the Set() and Get() methods respectively used to set the time once and to get updated time stamps afterward. The thermocouple communicates over SPI with the application. It exposes a Read() method which caches a raw temperature sample accessed through the Celsius and Fahrenheit properties. Note: the Netduino Plus already features a built-in microSD card reader, in which case, having another one on the shield is not really needed. Except for this hardware difference, everything else discussed within this article applies equally to the regular Netduino and the Netduino Plus. Interfacing with the Arduino Logger shield’s hardware Adafruit is pretty good about making usable products and generally provides Arduino libraries to use with their hardware. Indeed, the Arduino Logger Shield is well documented and comes with two C++ libraries: SD which implements a FAT file system and supporting low-level SD card I/O functions. RTCLib which wraps the I2C interface required to communicate with the DS1307 real time clock. The SD Card Interface Let’s deal with the SD card reader and the file system first: a quick review of SD.h reveals two C++ classes: • class File : public Stream {} exposing standard read, write, seek, flush file access functions. • class SDClass {} exposing storage management such as file and directory operations. This is good news because the .NET Micro Framework on the Netduino already supports file streams and directory management through the use of the .NET MF System.IO assembly. This assembly comes with the .NET MF SDK port to the Netduino. clip_image004 By the same token, interfacing with an SD card is provided by an assembly built by Secret Labs named SecretLabs.NETMF.IO which comes with the Netduino SDK. image SecretLabs.NETMF.IO provides two functions for 'mounting' and 'un-mounting' an SD card device and the associated FAT file system so that it can be made usable by the .NET MF through assemblies such as System.IO. It's important to note that the SecretLabs.NETMF.IO assembly must not be deployed with an application targeting the Netduino Plus: on boot, the .NET Micro Framework implementation specific to the Netduino Plus automatically detects and mounts the SD card if one is present in its microSD card reader. This functionality is redundant with the MountSD / Unmount functions provided by the SecretLabs.NETMF.IO assembly which is only needed on Netduino SKUs without a built-in SD card reader. How does the .NET MF interact with the SD card through the shield? At this point, it's a good time to review the Arduino Logger Shield's pin-out and the shield's schematics: image As we know from our previous article, pins D10-D13 map to the SPI interface and pins A4-A5 map to the I2C interface of the Netduino. On the shield's schematics, the SPI interface leads us to the SD & MMC section of the diagram, connected through a 74HC125N logic-level shifter chip indicated as IC3A-D. The role of the logic-level shifter is to ensure that logic voltages supplied to the SD card do not exceed 3.3v, even if they come from a microcontroller using 5v logic levels, such as the Arduino. When using an SD card with a Netduino, a level-shifter is not required since all logic levels run at 3.3v on the AT91SAM7x chip but it doesn't interfere with any I/O operations either when the voltage is already 3.3v. image The SD card reader in itself is just a passive connector, giving access to the controller built into the SD card. It also provides a mechanical means (i.e. switches) of detecting the presence of a card in the reader (see JP14 pin 1) as well as detecting if the card is write-protected (see JP14 pin 2). We'll make use of the card detection pin in the sample temperature logging application later on. For background on how SD cards work, the following application note "Secure Digital Card Interface for the MSP430" is excellent and much easier to digest than the extensive 'simplified' SD card protocol specifications provided on the SD Card Association site. The following table taken from the "Secure Digital Card Interface for the MSP430" shows the pin out of an SD card and the corresponding SPI connections: clip_image012 clip_image014 An SD standard-compliant card can support 3 distinct access modes, each one providing different performance characteristics: • SD 1-bit protocol: synchronous serial protocol with one data line, one clock line and one line for commands. The full SD card protocol command set is supported in 1-bit mode. • SD 4-bit protocol: this mode is nearly identical to the SD 1-bit mode, except that the data is multiplexed over 4 data lines, yielding up to 4x the performance of SD 1-bit mode. The full SD card protocol command set is supported in 4-bit mode. • SPI mode: provide a standard SPI bus interface (/SS, MOSI, MISO, SCK). In SPI mode, the SD card only supports a subset of the full SD card protocol but it is sufficient for implementing a fully functional storage mechanism with a file system. As you might have guessed, the .NET Micro Framework on the Netduino makes use of the SD card in SPI mode (see \DeviceCode\Drivers\BlockStorage\SD\SD_BL_driver.cpp). The block-oriented SD card I/Os are abstracted thanks to the FAT file system provided by the System.IO assembly (see \DeviceCode\Drivers\FS\FAT\FAT_FileHandle.cpp and FAT_LogicDisk.cpp). The role of the SecretLabs.NETMF.IO assembly on the Netduino (or its built-in equivalent on the Netduino Plus) is to initialize the SD card in SPI mode during the 'mounting' process by sending the proper set of commands as defined in the SD Card protocol. In the C# code of the AdafruitNetduinoLogger sample application, which we will review as a whole later on in the code walkthrough section, the following function takes care of the SD card initialization: public static void InitializeStorage(bool mount) { try { if (mount == true) { StorageDevice.MountSD(SdMountPoint, SPI.SPI_module.SPI1, Pins.GPIO_PIN_D10); } else { StorageDevice.Unmount(SdMountPoint); } } catch (Exception e) { LogLine("InitializeStorage: " + e.Message); SignalCriticalError(); } } Once mounted, the file system is accessed through System.IO calls such as this: using (var tempLogFile = new StreamWriter(filename, true)) { tempLogFile.WriteLine(latestRecord); tempLogFile.Flush(); } Using the StreamWriter class in this context made sense for writing strings as used in the sample application: clip_image016 However, there are many other file I/O classes available in System.IO that may be better suited depending on the scenario. The DS1307 real time clock Our next step is to examine the interface with the DS1307 real time clock (RTC). We'll start by extracting the most important parts of the DS1307 datasheet and reviewing how it's wired up on the shield's schematics. DS1307 features • Real-Time Clock (RTC) Counts Seconds, Minutes, Hours, Date of the Month, Month, Day of the week, and Year with Leap-Year Compensation Valid Up to 2100 • 56-Byte, Battery-Backed, General-Purpose RAM with Unlimited Writes • I2C Serial Interface • Programmable Square-Wave Output Signal • Automatic Power-Fail Detect and Switch Circuitry • Consumes Less than 500nA in Battery-Backup Mode with Oscillator Running Note: If you need to measure the time something takes in milliseconds, a time granularity that the DS1307 clock does not provide, you can use the Utility functions provided by the .NET Micro Framework like this: var tickStart = Utility.GetMachineTime().Ticks; // <...code to be timed...> var elapsedMs = (int)((Utility.GetMachineTime().Ticks - tickStart) / TimeSpan.TicksPerMillisecond); This timing method relies on the CPU's internal tick counter and is not 100% accurate due to the overhead of the .NET MF itself but may be sufficient in most scenarios. In addition, the internal tick counter rolls over every so often, something that should be taken into account in production code. DS1307 register map Accessing the clock's features comes down reading and writing to and from a set of registers as described on page 8 of the datasheet. clip_image018 Page 9 of the DS1307 datasheet provides more details about the square wave generation function of the clock, which we will not be using here. The generated square wave signal is available on the shield through connector JP14 on pin 3 as you can see on the schematics below and can be used to provide a slow but reliable external clock signal to another device such as a microcontroller. clip_image020 clip_image022 DS1307 I2C bus address The final piece of the puzzle needed before we can use the DS1307 is the device's address on the I2C data bus and its maximum speed (specified at 100 KHz on page 10 of the datasheet). The device address is revealed on page 12 as being 1101000 binary (0x68) along with the two operations modes (Slave Receiver and Slave Transmitter) of the clock. The 8th bit of the address is used by the protocol to indicate whether a 'read' or a 'write' operation is requested. Note: I2C devices sometime make use of 10-bit addresses. If you aren't familiar with the I2C data bus, you should read the section of the datasheet starting on page 10 which provides a good foundation for understanding how I2C generally works. It can be summarized as follows: • I2C is a 2-wire serial protocol with one bidirectional data line referred to as SDA and one clock line, referred to as SCL. • The I2C bus is an open-drain bus (i.e. devices pull the bus low to create a '0' and let go of the bus to create a '1'). To achieve this, I2C requires a pull-up resistor on the SCL and SDA lines between 1.8K ohms and 10K ohms. I2C devices do not need to provide pull-ups themselves if the bus already has them. • The I2C master (i.e. the Netduino microcontroller) always provides the clock signal, generally between 100 KHz (or lower) for standard speed devices or 400 KHz for high-speed devices. There's also a 'Fast Mode Plus' allowing for speeds up to 1MHz on devices supporting it. There can be more than one master on the bus even though this is uncommon. • An I2C device can have a 7-bit or 10-bit address, allowing for multiple I2C devices to be used on the same bus. • I2C read and write operations are transactions initiated by the I2C master targeting a specific device by address. Some I2C slave devices can notify their master that they need to communicate using a bus interrupt. • A transaction is framed by 'start' and 'stop signals, with each byte transferred requiring an acknowledgement signal. image image image At this point, we have all the pieces needed to communicate with the RTC using I2C transactions. Using the I2C protocol with the .NET Micro Framework On the Arduino, the library used with the shield to communicate with the DS1307 is a C++ library called RTClib. The header of the library declares a DateTime class, similar in functionality to the standard .NET Micro Framework DateTime class provided by System in the mscorlib assembly. We'll use the standard .NET MF data type to work with the clock instead. The next declared class is RTC_DS1307 which implements the driver for the DS1307 chip using the Wire library to wrap the I2C protocol. The .NET Micro Framework also supports the I2C protocol through to the Microsoft.SPOT.Hardware assembly. Here again, we'll use the .NET MF implementation of I2C in order to communicate with the clock. However, the I2C transaction patterns implemented by the C++ driver can still provide a useful guide for writing a C# driver for the DS1307 when you don't know where to begin just based on the datasheet. For instance, the following functions taken from RTClib.cpp shows the call sequence used with the Wiring API to address the date and time registers of the clock: int i = 0; //The new wire library needs to take an int when you are sending for the zero register void RTC_DS1307::adjust(const DateTime& dt) { Wire.beginTransmission(DS1307_ADDRESS); Wire.write(i); Wire.write(bin2bcd(dt.second())); Wire.write(bin2bcd(dt.minute())); Wire.write(bin2bcd(dt.hour())); Wire.write(bin2bcd(0)); Wire.write(bin2bcd(dt.day())); Wire.write(bin2bcd(dt.month())); Wire.write(bin2bcd(dt.year() - 2000)); Wire.write(i); Wire.endTransmission(); } DateTime RTC_DS1307::now() { Wire.beginTransmission(DS1307_ADDRESS); Wire.write(i); Wire.endTransmission(); Wire.requestFrom(DS1307_ADDRESS, 7); uint8_t ss = bcd2bin(Wire.read() & 0x7F); uint8_t mm = bcd2bin(Wire.read()); uint8_t hh = bcd2bin(Wire.read()); Wire.read(); uint8_t d = bcd2bin(Wire.read()); uint8_t m = bcd2bin(Wire.read()); uint16_t y = bcd2bin(Wire.read()) + 2000; return DateTime (y, m, d, hh, mm, ss); } The final class is RTC_Millis, a utility class converting time data into milliseconds, effectively providing the functionality of the DateTime.Millisecond property on the .NET MF. Having assessed that the functionality of RTClib only handles date and time registers and knowing the role of the other clock registers, we can proceed with implementing a complete DS1307 C# driver, supporting the square wave and RAM functions, using the native I2C protocol support of the .NET Micro Framework. The driver starts by defining key constants matching the clock registers according to the datasheet: [Flags] // Defines the frequency of the signal on the SQW interrupt pin on the clock when enabled public enum SQWFreq { SQW_1Hz, SQW_4kHz, SQW_8kHz, SQW_32kHz, SQW_OFF }; [Flags] // Defines the logic level on the SQW pin when the frequency is disabled public enum SQWDisabledOutputControl { Zero, One }; // Real time clock I2C address public const int DS1307_I2C_ADDRESS = 0x68; // Start / End addresses of the date/time registers public const byte DS1307_RTC_START_ADDRESS = 0x00; public const byte DS1307_RTC_END_ADDRESS = 0x06; // Start / End addresses of the user RAM registers public const byte DS1307_RAM_START_ADDRESS = 0x08; public const byte DS1307_RAM_END_ADDRESS = 0x3f; // Square wave frequency generator register address public const byte DS1307_SQUARE_WAVE_CTRL_REGISTER_ADDRESS = 0x07; // Start / End addresses of the user RAM registers public const byte DS1307_RAM_START_ADDRESS = 0x08; public const byte DS1307_RAM_END_ADDRESS = 0x3f; // Total size of the user RAM block public const byte DS1307_RAM_SIZE = 56; Next the driver defines an I2C device object representing the clock: // Instance of the I2C clock protected I2CDevice Clock; In the class constructor, the I2C clock device is initialized, specifying its address and speed in KHz: public DS1307(int timeoutMs = 30, int clockRateKHz = 50) { TimeOutMs = timeoutMs; ClockRateKHz = clockRateKHz; Clock = new I2CDevice(new I2CDevice.Configuration(DS1307_I2C_ADDRESS, ClockRateKHz)); } The driver retrieves the date and time from the clock through a Get function returning a DateTime object. public DateTime Get() { byte[] clockData = new byte [7]; // Read time registers (7 bytes from DS1307_RTC_START_ADDRESS) var transaction = new I2CDevice.I2CTransaction[] { I2CDevice.CreateWriteTransaction(new byte[] {DS1307_RTC_START_ADDRESS}), I2CDevice.CreateReadTransaction(clockData) }; if (Clock.Execute(transaction, TimeOutMs) == 0) { throw new Exception("I2C transaction failed"); } return new DateTime( BcdToDec(clockData[6]) + 2000, // year BcdToDec(clockData[5]), // month BcdToDec(clockData[4]), // day BcdToDec(clockData[2] & 0x3f), // hours over 24 hours BcdToDec(clockData[1]), // minutes BcdToDec(clockData[0] & 0x7f) // seconds ); } Let's break it down: • A 7-byte array is allocated which will receive the raw date and time data registers, starting at address DS1307_RTC_START_ADDRESS (0x00) and ending at DS1307_RTC_END_ADDRESS (0x06). • An I2C transaction object is allocated, comprising two parameters: • A 'write' transaction object telling the DS1307 device which register address to start reading data from. In this case, this is DS1307_RTC_START_ADDRESS (0x00), the very first time-keeping register. • A 'read' transaction object specifying where the clock's time-keeping data registers will be stored, implicitly defining the total number of bytes to be read and acknowledged. • Clock.Execute is the function calling into the .NET MF I2C interface to run the prepared transactions. The second parameter specifies a time out value expressed in milliseconds before the transaction fails, resulting in a generic exception being thrown. • When the transactions succeed, a DateTime object is instantiated with the 7 time-keeping registers returned by the 'read' transaction. Each register is converted from Binary Coded Decimal form to decimal form using a custom utility function: protected int BcdToDec(int val) { return ((val / 16 * 10) + (val % 16)); } Conversely, the driver provides a Set function to update the clock's time-keeping registers. Because the driver doesn't expect a response from the DS1307 in this scenario, the I2C transaction is write-only. The fields of the DateTime parameter corresponding to the time -keeping registers are converted from decimal form to BCD form and stuffed in a 7-byte array before executing the transaction. public void Set(DateTime dt) { var transaction = new I2CDevice.I2CWriteTransaction[] { I2CDevice.CreateWriteTransaction(new byte[] { DS1307_RTC_START_ADDRESS, DecToBcd(dt.Second), DecToBcd(dt.Minute), DecToBcd(dt.Hour), DecToBcd((int)dt.DayOfWeek), DecToBcd(dt.Day), DecToBcd(dt.Month), DecToBcd(dt.Year - 2000)} ) }; if (Clock.Execute(transaction, TimeOutMs) == 0) { throw new Exception("I2C write transaction failed"); } } The rest of the functions provided by the C# driver implement the other DS1307 features, such as • SetSquareWave • Halt • SetRAM • GetRAM • The [] operator used to access a specific clock register • WriteRegister In all case, these functions are wrappers around the 'read' and 'write' I2C transaction model, involving the appropriate DS1307 registers as defined in the datasheet.  Using the Adafruit Arduino Logger Shield as a temperature logger image To illustrate the points discussed so far, we'll use the Adafruit Arduino Logger shield with a Netduino and a MAX6675 thermocouple amplifier for the purpose of recording ambient temperature samples at ten second intervals. Each record includes a date, a time and the temperature expressed in Celsius and Fahrenheit. The records are written to daily files in CSV format for easy export to a spreadsheet, making the application easily adaptable for acquiring data from different sensors: Date Time Celsius Fahrenheit 6/14/2012 15:35:00:05 18.75 65.75 6/14/2012 15:35:10:05 18 64.4 6/14/2012 15:35:20:05 18.5 65.29 6/14/2012 15:35:30:05 18 64.4 6/14/2012 15:35:40:05 18 64.4 6/14/2012 15:35:50:05 18.75 65.75   Device Connections Instead of permanently soldering the temperature sensor to the prototyping area of the shield, female / female jumper wires were used to make connections between the shield's own pin headers as well as the thermocouple's male pin headers. LoggerShieldBoard The following table enumerates these connections: Shield Pin Destination Pin 3v (Power header) Max6675 VCC GND (Power or Digital I/O header) Max6675 GND D13 (Digital I/O header, SPI CLK) Max6675 CLK (SPI CLK) D12 (Digital I/O header, SPI MISO) Max6675 DO (SPI MISO) D2 (Digital I/O header, used as SPI /SS) Max6675 CS (SPI /SS) L1 (LEDS header) D1 (Digital I/O header) L2 (LEDS header) D0 (Digital I/O header) CD (SD card detect) D3 (Digital I/O header)   Reading temperature using an Adafruit Max6675 Thermocouple amplifier breakout board The Max6675 thermocouple amplifier chip on the breakout board is a read-only SPI device. When the CS pin (SPI /SS) of the device is asserted with a 1ms delay before reading, the chip returns a 12-bit value on its DO pin (SPI MISO) corresponding to the temperature measured by a K-type Thermocouple wire. The resulting C# driver for the Max6675 is short: using System; using Microsoft.SPOT; using Microsoft.SPOT.Hardware; namespace Maxim.Temperature{ public class Max6675 : IDisposable { protected SPI Spi; public void Initialize(Cpu.Pin chipSelect) { Spi = new SPI( new SPI.Configuration( chipSelect, false, 1, 0, false, true, 2000, SPI.SPI_module.SPI1) ); } public double Celsius { get { return RawSensorValue * 0.25; } } public double Farenheit { get { return ((Celsius * 9.0) / 5.0) + 32; } } protected UInt16 RawSensorValue; protected byte[] ReadBuffer = new byte[2]; protected byte[] WriteBuffer = new byte[2]; public void Read() { RawSensorValue = 0; Spi.WriteRead(WriteBuffer, ReadBuffer); RawSensorValue |= ReadBuffer[0]; RawSensorValue <<= 8; RawSensorValue |= ReadBuffer[1]; if ((RawSensorValue & 0x4) == 1) { throw new ApplicationException("No thermocouple attached."); } RawSensorValue >>= 3; } public void Dispose() { Spi.Dispose(); } ~Max6675() { Dispose(); } } } Temperature logger application walkthrough Let's review the key parts of the temperature logging application code and how it interacts with the devices connected to the shield. public static readonly string SdMountPoint = "SD"; Defines an arbitrary string used to refer to the SD card when using StorageDevice.MountSD and StorageDevice.Unmount functions. public static readonly int TemperatureLoggerPeriod = 10 * 1000; // milliseconds Defines the interval between temperature samples. public static OutputPort LedRed = new OutputPort(Pins.GPIO_PIN_D0, false); Defines an output connected to pin D0 controlling the state of the red LED on the shield. public static OutputPort LedGreen = new OutputPort(Pins.GPIO_PIN_D1, false); Defines an output connected to pin D1 controlling the state of the green LED on the shield. public static InputPort CardDetect = new InputPort( Pins.GPIO_PIN_D3, true, Port.ResistorMode.PullUp); Defines an input connected to pin D3 used to determine if an SD card is inserted in the SD socket. public static ManualResetEvent ResetPeripherals = new ManualResetEvent(false); Defines a manual reset event object that will be used in the main application loop to determine when to re-initialize the shield's peripherals. public static readonly Cpu.Pin ThermoCoupleChipSelect = Pins.GPIO_PIN_D2; Defines D2 as the SPI chip select pin connected to the Max6675 Thermocouple board. public static Timer TemperatureSampler; Defines an instance of a timer object which will drive temperature sampling. public static DS1307 Clock; Defines an instance of the DS1307 real time clock driver. public static Max6675 ThermoCouple; Defines an instance of the Max6675 thermocouple driver. public static ArrayList Buffer = new ArrayList(); Defines an array list instance which will be used as a temporary buffer when the SD card is removed from its socket. The application's main loop is only concerned about the state of the peripherals: • It initializes the devices connected to the shield • It waits indefinitely for a signal indicating that a hardware error occurred • It disposes of the current device instances and starts over public static void Main() { while (true) { InitializePeripherals(); ResetPeripherals.WaitOne(); ResetPeripherals.Reset(); DeInitializePeripherals(); } } InitializePeripherals indicates that it is working by controlling the green LED on the shield. Its role is focused on object creation and initialization. public static void InitializePeripherals() { LedGreen.Write(true); Clock = new DS1307(); ThermoCouple = new Max6675(); InitializeStorage(true); InitializeClock(new DateTime(2012, 06, 14, 17, 00, 00)); ThermoCouple.Initialize(ThermoCoupleChipSelect); TemperatureSampler = new Timer( new TimerCallback(LogTemperature), null, 250, TemperatureLoggerPeriod); LedGreen.Write(false); } If the initialization of a peripheral fails, the shield will quickly blink its LEDs, indefinitely: public static void SignalCriticalError() { while (true) { LedRed.Write(true); LedGreen.Write(true); Thread.Sleep(100); LedRed.Write(false); LedGreen.Write(false); Thread.Sleep(100); } } The clock initialization function only sets the clock date and time when it is unable to find a file named 'clockSet.txt' on the SD card, ensuring that the initialization of the DS1307 only happens once in the InitializePeripherals function or until the file is deleted. public static void InitializeClock(DateTime dateTime) { var clockSetIndicator = SdMountPoint + @"\clockSet.txt"; try { if (File.Exists(clockSetIndicator) == false) { Clock.Set(dateTime); Clock.Halt(false); File.Create(clockSetIndicator); } } catch (Exception e) { LogLine("InitializeClock: " + e.Message); SignalCriticalError(); } } The LogTemperature function is the callback invoked by the Timer object every 10 seconds. The function indicates that it is working by turning the red LED on the shield ON and OFF. public static void LogTemperature(object obj) { LedRed.Write(true); } The function reads the current time from the clock with Clock.Get() and takes a temperature sample with ThermoCouple.Read(). var tickStart = Utility.GetMachineTime().Ticks; var now = Clock.Get(); ThermoCouple.Read(); var elapsedMs = (int)((Utility.GetMachineTime().Ticks - tickStart) / TimeSpan.TicksPerMillisecond); Then, it concatenates a string containing the date, time and temperature expressed in Celsius and Fahrenheit, with each field separated by commas. var date = AddZeroPrefix(now.Year) + "/" + AddZeroPrefix(now.Month) + "/" + AddZeroPrefix(now.Day); var time = AddZeroPrefix(now.Hour) + ":" + AddZeroPrefix(now.Minute) + ":" + AddZeroPrefix(now.Second) + ":" + AddZeroPrefix(elapsedMs); var celsius = Shorten(ThermoCouple.Celsius.ToString()); var farenheit = Shorten(ThermoCouple.Farenheit.ToString()); var latestRecord = date + "," + time + "," + celsius + "," + farenheit; To make the data more manageable, daily temperature files are created as needed, each one starting with the column headers expected for parsing the values in CSV format. var filename = SdMountPoint + BuildTemperatureLogFilename(now); if (File.Exists(filename) == false) { using (var tempLogFile = new StreamWriter(filename, true)) { tempLogFile.WriteLine("date,time,celsius,fahrenheit"); } } The temperature sampling application lets the user remove the SD card from its socket so that the CSV files can be moved over to a PC for processing without losing data in the meantime. In order to do this, the application checks the state of the 'Card Detect' pin before attempting file system I/Os. When the SD card is not present, the latest temperature record is preserved in the array list buffer until the SD card is put back in its socket. The array list data is then flushed to storage. if (CardDetect.Read() == false) { using (var tempLogFile = new StreamWriter(filename, true)) { if (Buffer.Count != 0) { foreach (var bufferedLine in Buffer) { tempLogFile.WriteLine(bufferedLine); } Buffer.Clear(); } tempLogFile.WriteLine(latestRecord); tempLogFile.Flush(); } } else { LogLine("No card in reader. Buffering record."); Buffer.Add(latestRecord); } The temperature logging function expects to run out of memory if the array list buffer grows too large, in which case, all the records get purged. Other memory management strategies could be used to mitigate data loss in this case. However, this depends entirely on the requirements of the data logging application and is out of scope for this discussion. catch (OutOfMemoryException e) { LogLine("Memory full. Clearing buffer."); Buffer.Clear(); } The temperature logging function also handles file system exceptions caused by the removal of the SD card and reacts by signaling the ResetPeripherals event. In turn, this lets the application's main loop know that the peripherals, and most specifically the SD card, need to be recycled and initialized again in order to recover from the error. catch (IOException e) { LogLine("IO error. Resetting peripherals."); Buffer.Add(latestRecord); ResetPeripherals.Set(); } Conclusion In this article, we took a shield designed for the Arduino and learned how to critically review the Arduino code libraries supporting it, drawing parallels with features offered by the .NET Micro Framework. This process allowed us to identify areas in the Arduino code which were not necessary to port over to C# such as SD card and file system handlers. It also allowed us to see the similarities in the way the Arduino and the Netduino handle I2C communications. Most importantly, we also learned the importance of reviewing a device's schematics and component datasheets to ensure that important features have not been omitted and potentially incorrectly implemented when considering using an unknown library: in the case of RTClib, we saw that the implementation was limited to the basic date and time functions of the DS1307, leaving out other useful features such as the clock's built-in RAM and the square wave generation functions. In our next article, we'll take on a much more complex shield and we will learn how to analyze Arduino libraries in depth before porting them from C/C++ to C#. Bio Fabien is the Chief Hacker and co-founder of Nwazet, a start-up company located in Redmond WA, specializing in Open Source software and embedded hardware design. Fabien's passion for technology started 30 years ago, creating video games for fun and for profit. He went on working on mainframes, industrial manufacturing systems, mobile and web applications. Before Nwazet, Fabien worked at MSFT for eight years in Windows Core Security, Windows Core Networking and Xbox. During downtime, Fabien enjoys shooting zombies and watching sci-fi. ]]> https://channel9.msdn.com/coding4fun/articles/Using-the-Adafruit-Arduino-Logger-Shield-on-a-Netduino C9 Netduino Shield Series - Using Arduino Shields with a Netduino - Part II IntroductionIn our previous article, we examined what an Arduino shield is, how to build a simple custom shield and discussed how to quickly identify shields that are good candidates for a Netduino adaptation versus shields that may not be. In this article, we’ll take a popular Arduino Logger Shield produced by Adafruit and we’ll interface it with a Netduino / Plus microcontroller The Arduino Logger Shield is an excellent one to start with because it offers immediate benefits to a Netduino / Plus user: Time-keeping SD card storage Two user-controllable LEDs A small prototyping area An onboard 3.3v voltage regulator for clean analog readings and power decoupling In our C# data logging application, we'll interact with the time keeper, the SD card storage and its 'card detect' pin, the two LEDs as well as a temperature sensor (not included with the shield). Before diving into the details associated with the hardware, you may want to take a look at the C# objects representing the hardware: public static readonly string SdMountPoint = &quot;SD&quot;; public static OutputPort LedRed = new OutputPort(Pins.GPIO_PIN_D0, false); public static OutputPort LedGreen = new OutputPort(Pins.GPIO_PIN_D1, false); public static InputPort CardDetect = new InputPort(Pins.GPIO_PIN_D3, true, Port.ResistorMode.PullUp); public static readonly Cpu.Pin ThermoCoupleChipSelect = Pins.GPIO_PIN_D2; public static DS1307 Clock; public static Max6675 ThermoCouple; and their initialization: public static void InitializePeripherals() { LedGreen.Write(true); Clock = new DS1307(); ThermoCouple = new Max6675(); InitializeStorage(true); InitializeClock(new DateTime(2012, 06, 14, 17, 00, 00)); ThermoCouple.Initialize(ThermoCoupleChipSelect); TemperatureSampler = new Timer(new TimerCallback(LogTemperature), null, 250, TemperatureLoggerPeriod); LedGreen.Write(false); } The SD car https://channel9.msdn.com/coding4fun/articles/Using-the-Adafruit-Arduino-Logger-Shield-on-a-Netduino Thu, 23 Aug 2012 17:30:00 GMT https://channel9.msdn.com/coding4fun/articles/Using-the-Adafruit-Arduino-Logger-Shield-on-a-Netduino Fabien Royer Fabien Royer 3 https://channel9.msdn.com/coding4fun/articles/Using-the-Adafruit-Arduino-Logger-Shield-on-a-Netduino/RSS .NET Micro Framework Hardware What Is an Arduino Shield and Why Should My Netduino Care? C9 Netduino Shield Series - Using Arduino Shield with Netduino - Part I clip_image001_thumb1  Photo courtesy of John Boxall Introduction When the Arduino Duemilanove microcontroller appeared in 2005, it featured a set of female pin headers exposing most of the pins of the ATmega168 for easy hacking and for connecting accessory boards known as 'Shields'. The purpose of a shield is to provide new plug-and-play functionality to the host microcontroller, such as circuit prototyping, motion control, sensor integration, network and radio communication, or gaming interfaces, without worrying too much about the hardware implementation details. Seven years after the birth of the original Arduino, new shields keep coming out and are being cataloged on http://shieldlist.org/, a testament to the versatility of the design. It is also simple to build a DIY shield when nothing out there will meet your needs or when you want to understand how the shield concept works from the ground up. In their infinite wisdom, Secret Labs, the makers of the Netduino, adopted the same Arduino form factor and header pin out to let .NET Micro Framework users tap into the vast array of Arduino shields on the market. Yet, there's always one hurdle that needs to be overcome: in order to give access to their hardware functions easily, many Arduino shields provide sample sketches (a.k.a. C/C++ Wiring programs) and libraries also written in C/C++ designed to be used within the Arduino IDE. Unfortunately, Arduino sketches and libraries aren't compatible with the Visual Studio environment and the .NET runtime: they need to be adapted in order to make use of the shield's hardware. The goal of this series of articles is to attempt to demystify what an Arduino shield is. To do this, we'll start by building one from scratch. Then, we'll present a generic approach for selecting Netduino-compatible Arduino shields and adapting Arduino code to interface with the .NET Micro Framework. Selecting Arduino shields for use with Netduino / Plus Arduino shields using hardware components interfaced over protocols such as SPI, I2C, 1-Wire or serially over a UART are generally good candidates for a Netduino adaptation because the .NET Micro Framework supports these protocols natively and can do bulk I/O transfers, yielding good performance. However, if a shield requires bit-banging data on GPIOs (i.e. communicating data serially, such as SPI, I2C, RS-232, in software by toggling GPIO lines individually instead of using dedicated hardware interfaces) or has very low I/O latency requirements, it may not be practical or even possible to use the shield on a Netduino / Plus. The reason for this is simple: the Arduino runs native code and can access hardware registers directly with a latency orders of magnitude lower than what the .NET Micro Framework can achieve on a Netduino / Plus where toggling GPIOs means going through multiple framework layers while running interpreted code. The maximum raw I/O toggling frequency on a Netduino / Plus clocked at 48 MHz was measured around ~8.4KHz which is slow compared to the few MHz achievable on an Arduino clocked at 16 MHz. Fortunately, there are possible workarounds and strategies • Whenever an Arduino library bit-bangs SPI data on GPIOs, regardless of the pins used to do it, it can be replaced by using the standard SPI interface on the Netduino / Plus. • The Netduino / Plus has significantly more RAM available than the Arduino and can transfer larger SPI data buffer in a single shot, dramatically reducing I/O latency. For instance, driving a display shield would greatly benefit from this method where a frame is cached in RAM on the Netduino / Plus then sent in one shot over SPI to the hardware display driver. The bottom line is that it is always a good idea to review how the Arduino code interfaces with a given shield before proceeding with a purchase or starting a conversion project. This review process is also facilitated by http://shieldlist.org which shows which pins are being used to drive a shield. For example, the Adafruit Industries Logger Shield uses hardware SPI (pins D10-D13) for the SD card and I2C (pins A4-A5) for the DS1307 real time clock, making it a perfect adaptation candidate for the Netduino / Plus as we'll see in our next article. imageimage It's also very important to know what features are available on the .NET Micro Framework running on the Netduino / Plus: some things come standard with the .NET Micro Framework which normally require add-ons libraries on the Arduino such as file system and networking support. Finally, it is wise to search code repositories such as CodePlex, BitBucket and GitHub for hardware drivers and libraries before undertaking writing one in C# from scratch based on component datasheets. This extends to the Netduino and the TinyCLR community forums where many people have posted drivers in discussion threads. Building a shield from scratch to meet specific requirements Recently, we were asked if it was possible to connect our Touch Display module designed for a Netduino Go! to a Netduino / Plus. By doing a bit of research and seeing how the driver for the Touch Module works, this can be done by building a simple custom shield composed of a few parts connecting the Netduino pin headers to a Netduino Go! socket breakout board like so: FinishedCustomShieldGoTouchDisplayOnNetduino High-Level Software Interface To frame the rest of this article, the communication interface with the shield is done using SPI and a GPIO used for synchronization. The communication protocol details are wrapped in the Nwazet.Go.Display.Imaging.VirtualCanvas class which needs to be initialized with the SPI and GPIO parameters matching the pin out of the shield: var canvas = new VirtualCanvas(TouchEventHandler, WidgetClickedHandler); canvas.Initialize( displaySpi: SPI.SPI_module.SPI1, displayChipSelect: Pins.GPIO_PIN_D9, displayGPIO: Pins.GPIO_PIN_D8, speedKHz: 5000); From that point on, all interactions with the shield are done through Draw* methods followed by a call to the Execute() method which handles sending and receiving SPI data packets. The VirtualCanvas class also provides methods for creating widgets such as buttons, receiving touch screen events and setting the screen orientation. For example, the following code snippet draws and updates a progress bar and uses one of the proportional fonts built into the display: public static void Main() { var canvas = new VirtualCanvas(); canvas.Initialize( displaySpi: SPI.SPI_module.SPI1, displayChipSelect: Pins.GPIO_PIN_D9, displayGPIO: Pins.GPIO_PIN_D8, speedKHz: 5000); var fontInfo = new DejaVuSans9().GetFontInfo(); canvas.DrawFill(0xFFFF); canvas.DrawString(5, 144, (ushort)BasicColor.Black, fontInfo.ID, "Progress"); for (var progress = 1; progress <= 100; progress++) { canvas.DrawProgressBar( 70, 140, 75, 12, RoundedCornerStyle.All, RoundedCornerStyle.All, (ushort)BasicColor.Black, (ushort)GrayScaleValues.Gray_128, (ushort)GrayScaleValues.Gray_30, (ushort)BasicColor.Green, progress); Thread.Sleep(100); canvas.Execute(); } } Netduino Go! Socket Pin Out In order to build the shield, we need to start with mapping out the connections between the Go! bus socket and the header pins of the shield. The Go! socket pin out was designed by Secret Labs to be compatible with Gadgeteer modules supporting the following socket types: S (SPI), U (UART), X (3 GPIO) as documented in the .NET Gadgeteer Mainboard Builder's Guide v 1.8, page 6. This makes our little shield compatible with a Gadgeteer board as long as it is connected to an S socket. As far as other .NET Micro Framework boards are concerned, they should also work fine if they can drive an SPI slave device at 5 MHz, the minimum SPI clock frequency required by the Touch Display module. Gadgeteer Socket Types image Netduino Go! Socket image The hardware specifications of the Netduino / Plus tells us that the Netduino GPIOs correspond exactly to the Arduino Uno GPIOs: • digital pins 0-1: UART 1 RX, TX • digital pins 2-3: UART 2 RX, TX • digital pins 5-6: PWM, PWM • digital pins 7-8: UART 2 RTS, CTS • digital pins 9-10: PWM, PWM • digital pins 11-13: SPI MOSI, MISO, SPCK • analog pins 4-5: I2C SDA, SCL With this information, we can proceed with the creation of schematics to bridge the gap between the two worlds. Shield schematics What is a shield schematics How does this custom shield work? The Netduino Go! bus is designed around the SPI protocol (see Go! socket pins 6-10) which the Netduino / Plus can speak easily, making a Netduino Go! module or a S-type Gadgeteer module appear like any other SPI device to a Netduino / Plus. You will notice that the following pins aren't connected on the Go! socket for the sake of simplification: • Pin 2 (5v power): the Touch Display module operates on 3.3v, therefore the 5v power supply is not needed but could be connected to the 5v header of the Netduino to be fully compliant. • Pin 4 and 5 (UART): the Touch Display module does not make use of the serial interface during normal operation, so these lines can remain disconnected. However, to be fully compliant, Pin 4 (RX) and 5 (TX) on the Go! socket could be respectively connected to Netduino pin D1 (TX) and D0 (RX). • The fact that these lines aren't connected in this specific scenario would cause another module requiring a UART and/or 5v to not work obviously. While the SPI part is straight forward, there's a bit more to the Go! bus electrical specification that must be taken into account: the Netduino Go! bus also uses its GPIO pin on boot (see Go! socket pin 3) to control the behavior of modules based on ARM Cortex chips: when the GPIO pin is held HIGH on module power-up, the ARM Cortex chip enters its bootloader mode and waits to be flashed with new firmware over the Go! bus UART (see Go! socket pins 4-5). The ARM Cortex bootloader remains active until the ARM Cortex chip is reset or power-cycled. This is important to know for two reasons: 1. The Touch Display module is powered by an ARM Cortex M3 chip. 2. On boot, a Netduino / Plus sets all of its I/O pins HIGH, preventing the Touch Display from booting its firmware, which is undesirable. The reason for the I/O pins being set HIGH is documented on page 5 of the ATMEL AT91SAM7X datasheet which states that the pins on Parallel IO Controller A and B (PA0 - PA30 and PB0 - PB30) are pulled-up input at reset. The pins stay in that HIGH state until they're reconfigured by the Tiny CLR and the C# application itself. clip_image002 For this reason, the custom shield is designed to control the power supply of the Touch Display module through a general-purpose 2N4403 PNP transistor (see T1_PNP on the shield schematics) connected to pin D7: it is only when the base of the transistor is asserted LOW that power flows to the Touch Display module, countering the behavior of the Netduino / Plus on boot. In addition, the Netduino / Plus controls the state of the Go! bus GPIO pin through D8, asserting it LOW before powering up the Touch Display module. About the 2N4403 transistor: any other PNP transistor, or a P-Channel MOSFET, capable of switching at least 150mA continuously, the maximum current consumption of the touch display with some headroom, would have worked equally as well. The 2N4403 used here is more than adequate: image In the context of this shield, the PNP transistor is used as a switch, either fully ON or OFF, as opposed to being used as an amplifier. To this end, a 1K ohm resistor is used between the base of the transistor and Netduino / Plus pin D7 (POWER_CTRL) to ensure that the transistor is fully saturated but also limiting the maximum current sunken through pin D7 and potential damage being done to the ATMEL chip. The 10K ohm pull-up resistor placed between the base of the transistor and the 3.3v power rail ensures that the transistor will always be turned off by default, even when pin D7 is floating (i.e. not specifically declared as an Input or as an Output and driven HIGH or LOW by the C# application). The PowerUpDisplay function summarizes the interaction with the module through the shield on boot: // Pin connected to the transistor controlling the display's power supply public static OutputPort PowerTransistor = new OutputPort(Pins.GPIO_PIN_D7, true); public static void PowerUpDisplay() { // Ensure that the GPIO pin in low to prevent the display module to start in bootloader mode var goBusGPIO = new OutputPort(Pins.GPIO_PIN_D8, false); // Power up the display module PowerTransistor.Write(false); // Always wait 250ms after power-up to ensure that the display module is fully initialized before sending commands Thread.Sleep(250); goBusGPIO.Dispose(); } Refactoring a Netduino Go! C# driver to work on a regular Netduino / Plus The final step to get the Touch Display module working outside of its natural environment involved refactoring its C# driver (VirtualCanvas.cs), eliminating the idiosyncrasies specific to Netduino Go! bus. Go! modules are supposed to implement the GoModule interface as defined by the Netduino Go! SDK. Because the regular Netduino / Plus SDK has no knowledge of this interface, it's necessary to strip out any references and API calls specific to the Go! framework, leaving only what's absolutely required to communicate with the Touch Display module over SPI and maintaining the disposable nature of the class. For more details on Go! SDK, please refer to the Netduino Go! community forums and the source code of the existing module drivers as it is currently the best source of documentation. This step is akin to the work required when adapting an Arduino library to run on the .Net Micro Framework, only in this case, the task is easier since we're dealing with a C# driver to begin with instead of going from C/C++ to C#. Starting from the top of VirtualCanvas.cs, the following changes were made in the Netduino / Plus version of the driver: • Removed • using GoBus; • Replaced • public class VirtualCanvas : GoModule • with: public class VirtualCanvas : IDisposable • Replaced • public void Initialize(GoSocket socket, uint speedKHz = 25000) • with: public void Initialize(SPI.SPI_module displaySpi, Cpu.Pin displayChipSelect, Cpu.Pin displayGPIO, uint speedKHz = 25000). The core of the function simply initializes the SPI interface. • Replaced • protected override void Dispose(bool disposing) • with: public void Dispose() also removing the following calls: • SetSocketPowerState(false); this call is used by the GoModule object model to control when a socket is powered ON / OFF and is no longer applicable when the VirtualCanvas class is not derived from GoModule. • base.Dispose(disposing); by the same token, deriving from GoModule requires overriding the behavior of the Dispose function and calling the base class at the end, something that is no longer needed now that the class implements the regular IDisposable interface. • Moved • GoBusIrqEvent.Reset(); from WaitUntilGoBusIrqIsAsserted() • to: Execute(Synchronicity sync = Synchronicity.Synchronous) taking into account the higher latency of the Netduino / Plus The rest of the code remained unchanged. The Netduino / Plus Touch Display driver and test application for this custom shield can be downloaded from the Netudino Helpers project on CodePlex in the \Samples\Coding4Fun directory. Conclusion With nearly 300 known Arduino shields on the market, there's a wide variety of plug-and-play functionality waiting to be leveraged by the Netduino community, sometime with little or no software work required. When all else fails, building a shield from scratch to get a desired feature onto a Netduino / Plus is a relatively simple process only requiring reading component datasheets and some patience with a soldering iron or a small breadboard. In our next article, we'll put these guidelines to the test with a simple and popular off-the-shelf data logger shield made by Adafruit Industries. Appendix To build the shield interfacing with the [nwazet Touch Display, you will need the following parts: Custom shield Eagle schematics Bill of materials (~$15 for the shield w/o the [nwazet Touch Display module) Eagle libraries Netduino Go! Wiki Bio Fabien is the Chief Hacker and co-founder of Nwazet, a start-up company located in Redmond WA, specializing in Open Source software and embedded hardware design. Fabien's passion for technology started 30 years ago, creating video games for fun and for profit. He went on working on mainframes, industrial manufacturing systems, mobile and web applications. Before Nwazet, Fabien worked at MSFT for eight years in Windows Core Security, Windows Core Networking and Xbox. During downtime, Fabien enjoys shooting zombies and watching sci-fi. ]]> https://channel9.msdn.com/coding4fun/articles/What-Is-an-Arduino-Shield-and-Why-Should-My-Netduino-Care C9 Netduino Shield Series - Using Arduino Shield with Netduino - Part I Photo courtesy of John Boxall IntroductionWhen the Arduino Duemilanove microcontroller appeared in 2005, it featured a set of female pin headers exposing most of the pins of the ATmega168 for easy hacking and for connecting accessory boards known as 'Shields'. The purpose of a shield is to provide new plug-and-play functionality to the host microcontroller, such as circuit prototyping, motion control, sensor integration, network and radio communication, or gaming interfaces, without worrying too much about the hardware implementation details. Seven years after the birth of the original Arduino, new shields keep coming out and are being cataloged on http://shieldlist.org/, a testament to the versatility of the design. It is also simple to build a DIY shield when nothing out there will meet your needs or when you want to understand how the shield concept works from the ground up. In their infinite wisdom, Secret Labs, the makers of the Netduino, adopted the same Arduino form factor and header pin out to let .NET Micro Framework users tap into the vast array of Arduino shields on the market. Yet, there's always one hurdle that needs to be overcome: in order to give access to their hardware functions easily, many Arduino shields provide sample sketches (a.k.a. C/C&#43;&#43; Wiring programs) and libraries also written in C/C&#43;&#43; designed to be used within the Arduino IDE. Unfortunately, Arduino sketches and libraries aren't compatible with the Visual Studio environment and the .NET runtime: they need to be adapted in order to make use of the shield's hardware. The goal of this series of articles is to attempt to demystify what an Arduino shield is. To do this, we'll start by building one from scratch. Then, we'll present a generic approach for selecting Netduino-compatible Arduino shields and adapting Arduino code to interface with the .NET Micro Framework. Selecting Arduino shields for u 119 https://channel9.msdn.com/coding4fun/articles/What-Is-an-Arduino-Shield-and-Why-Should-My-Netduino-Care Mon, 23 Jul 2012 05:30:00 GMT https://channel9.msdn.com/coding4fun/articles/What-Is-an-Arduino-Shield-and-Why-Should-My-Netduino-Care Brian Peek, Fabien Royer Brian Peek, Fabien Royer 2 https://channel9.msdn.com/coding4fun/articles/What-Is-an-Arduino-Shield-and-Why-Should-My-Netduino-Care/RSS Project Detroit: Lighting System In this article, we give a detailed look into the external lighting system of Project Detroit, the Microsoft-West Coast Custom Mustang creation. If you're not already familiar with this project, you can find more information here. Overview The external lighting system for Project Detroit is run on a web server on a Netduino Plus, which uses the .NET Micro Framework (NETMF). To get an accelerated start, we leveraged code from the CodePlex project Netduino Helpers to control the AdaFruit LPD8806 LED strip, and the web server base code from the Netduino forums. They have been tweaked slightly for our project. netduino Controllers, Routes, RESTful oh my! We wanted the NETMF web server to have the exact same routes as the full-blown REST service layer in Detroit. With compiler conditionals, this allowed the same code to use the same routes on both the full .NET stack and NETMF. Since we couldn't use the ASP.NET MVC framework here, we had to make something close to it. Controllers Controllers implement an interface with a method named ExecuteAction. When GetController is called, we return the correct controller but cast as the interface IController. This lets us figure out what controller should be executing the request and continue to work generically in the context of the request connection thread. If new functionality is needed, we create a new controller that inherits from IController and update GetController: private static void RequestReceived(Request request) { // url comes in as /foo/bar/12345?style=255 // // /CONTROLLER/ACTION/ // // LIGHTING SAMPLE URL: /0/1/?r=255&g=255&b=255&zone=EnumAsInt // /0/... 0 = NetduinoControllerType.Lighting var validResponse = false; try { Logger.WriteLine("Start: " + request.Url + " at " + DateTime.Now); var urlInParts = request.Url.TrimStart(UriPathSeparator).Split(new[] {'?'}, 2); string[] uriSubParts = null; string[] queryStringSubParts = null; if (urlInParts.Length > 0) uriSubParts = urlInParts[0].Split(UriPathSeparator); if (urlInParts.Length > 1) queryStringSubParts = urlInParts[1].Split(QueryStringSeparator); if (uriSubParts != null && uriSubParts.Length > 1) { var targetController = GetController(uriSubParts[0]); if (targetController != null) { var action = (uriSubParts.Length >= 2) ? uriSubParts[1] : string.Empty; var result = targetController.ExecuteAction(action, queryStringSubParts); validResponse = true; request.SendResponse(result.ToString()); Logger.WriteLine("Result: " + result + " from " + request.Url + " at " + DateTime.Now); } } if (!validResponse) { SendIndexHtml(request); } } catch(Exception ex0) { Logger.WriteLine(ex0.ToString()); } } Routes, strings and enums on NETMF NETMF can't parse an enum from a string, which is something that can be done in the full .NET Framework. But what does this actually mean? It means the routes for the NETMF web server are a bit unreadable. Here is the same route but with the parsing issue exposed: Detroit's REST service route with ASP.NET MVC: http://…/Lighting/Solid/?zone=all&r=255&g=0&b=0 Detroit's NETMF route: http://…/0/3/?zone=0&r=255&g=0&b=0 This issue made direct device debugging a bit harder. Parsing the Action and query string Parsing the route is broken into two parts. The first is determines what controller to target. For Project Detroit, that meant the lighting system or the rear glass system. Once we know the controller, we still need to parse the query string and action into something more useful: #if NETMF private static readonly char[] QueryStringParamSeparator = new[] { '=' }; public static LightingData ParseQueryStringValues(string action, params string[] queryStringParameters) #else public static LightingData ParseQueryStringValues(string action, Dictionary<string, object> queryStringParameters) #endif { var data = new LightingData {LightingZone = LightingZoneType.All, LightingAction = ParseLightingActionType(action)}; #if NETMF if (queryStringParameters != null) { foreach (var queryString in queryStringParameters) { var valueKey = queryString.Split(QueryStringParamSeparator); if (valueKey.Length != 2) continue; var key = valueKey[0]; var value = valueKey[1]; #else foreach(var key in queryStringParameters.Keys) { var value = queryStringParameters[key].ToString(); #endif switch (key.ToLower()) { case ZoneHuman: case ZoneComputer: data.LightingZone = ParseLightingZoneType(value); break; // more stuff } } #if NETMF } #endif // more stuff return data; } Turning on the lights Individually addressable LED strips allow us to tell each individual LED what color to be. To adjust the colors of the LED lights, we loop through all the LEDs, set their color value, and then call LedRefresh() on our LED strip. There's no need to set all of them, only the ones being updated: private static void SolidAnimationWorker() { var leds = GetLedsToIlluminate(); var dataCopy = _data; for (var i = 0; i < leds.Length; i++) SetLed(leds[i], dataCopy.Red, dataCopy.Green, dataCopy.Blue); LedRefresh(); } Zones / Animation Threads A solid color is boring, but we can use procedural animations to add some flair. The current code supports the following animations: • Solid - A single solid color. • Fill - Goes from black to the desired color. The color stays lit. Much like filling a glass of liquid. Smiley • Random - LEDs are set to a random value. • Pulse - A glowing effect from bright to black. • Snake - A one way lighting effect with a fading tail that moves left to right. • Sweep - This effect was inspired by KITT and a Cylon robot and is similar to a snake pattern. The effect can also handle being split in two while maintaining a continual line for items such as the grill or the wheels. • Police - Each side flashes a red and blue light. Since we know the LED strip is a single strand, we can be clever with offsets and create groupings. By having a dedicated animation thread in each zone, we can have the grill of the car in Police Mode while the bottom fades to red and the vents fill to blue at different refresh rates. To run an animation, we need to first kill the old animation thread, spin up a new thread, mark LEDs in the "All LED" zone as do not touch, and execute the new pattern. Without a way to mark the LEDs as "bad" in the "All" zone, the two animation threads would compete for setting the color and result in a flickering effect. Other zones don't have to worry about this since there is zero overlap of LEDs:  public bool ExecuteAction(string action, params string[] queryStringParameters) { var data = LightingDataHelper.ParseQueryStringValues(action, queryStringParameters); SignalToEndAnimationThread(data.LightingZone); int counter = 0; while (counter++ < 5 && IsThreadAlive(data.LightingZone)) Thread.Sleep(10); if (IsThreadAlive(data.LightingZone)) AbortAnimationThread(data.LightingZone); // moving data bucket into public so new threads can leverage it _data = data; if (_data.LightingAction == LightingActionType.Police || _data.LightingAction == LightingActionType.Sweep) { _data.LightingZone = LightingZoneType.Grill; if (IsThreadAlive(_data.LightingZone)) AbortAnimationThread(_data.LightingZone); } // cleaning up just incase if (data.LightingZone != LightingZoneType.All) { for (var i = 0; i < _zoneAllAnimation.Length; i++) { var leds = GetLedsToIlluminate(); for (var z = 0; z < leds.Length; z++) { // flagging item as bad in animation lib if (_zoneAllAnimation[i] == leds[z]) _zoneAllAnimation[i] = -1; } } } switch (_data.LightingAction) { case LightingActionType.Solid: Debug.Print("Solid"); ExecuteThread(SolidAnimationWorker); break; // more patterns } return true; } We can now do something more interesting, like Police Mode: private static void PoliceModeAnimationWorker() { var leds = GetLedsToIlluminate(); var dataCopy = _data; var length = leds.Length; var half = length / 2; var index = 0; while (IsThreadSignaledToBeAlive(dataCopy.LightingZone)) { int redIntensity = (index == 0) ? 255 : 0; int blueIntensity = (index == 0) ? 0 : 255; for (var i = 0; i < half; i++) SetLed(leds[i], redIntensity, 0, 0); for (var i = half; i < length; i++) SetLed(leds[i], 0, 0, blueIntensity); LedRefresh(); index++; index %= 2; Thread.Sleep(100); } } WP_000197 Improvements Hindsight is 20/20. Nothing is ever perfect and there are of course items we'd love to change. At the start, the goal was to make this fairly generic and not Project Detroit "aware." As you can see by looking at the source, that wasn't accomplished due to time constraints. We would use a different LED system for two reasons: data transfer speed and power. The longer the LED strip is, the longer it takes to address an item further down the line. Project Detroit, having 15 meters of lighting in it, was impacted by this issue. It works well, just not as well as we hoped. The voltage requirements of the LEDs are another consideration. They are 5V, while a car uses 12V. Had we used 12V LEDs, our wiring would have been far simpler and wouldn't have required multiple transformers to get the required amperage needed at the correct voltage. Conclusion We think the lighting solution, coupled with the time and material constraints, worked out pretty well.  Project Detroit was a ton of fun to build out and working with West Coast Customs was the chance of a lifetime. Generic Episode Image ]]> https://channel9.msdn.com/coding4fun/articles/Project-Detroit-Lighting-System In this article, we give a detailed look into the external lighting system of Project Detroit, the Microsoft-West Coast Custom Mustang creation. If you're not already familiar with this project, you can find more information here. OverviewThe external lighting system for Project Detroit is run on a web server on a Netduino Plus, which uses the .NET Micro Framework (NETMF). To get an accelerated start, we leveraged code from the CodePlex project Netduino Helpers to control the AdaFruit LPD8806 LED strip, and the web server base code from the Netduino forums. They have been tweaked slightly for our project. Controllers, Routes, RESTful oh my!We wanted the NETMF web server to have the exact same routes as the full-blown REST service layer in Detroit. With compiler conditionals, this allowed the same code to use the same routes on both the full .NET stack and NETMF. Since we couldn't use the ASP.NET MVC framework here, we had to make something close to it. ControllersControllers implement an interface with a method named ExecuteAction. When GetController is called, we return the correct controller but cast as the interface IController. This lets us figure out what controller should be executing the request and continue to work generically in the context of the request connection thread. If new functionality is needed, we create a new controller that inherits from IController and update GetController: private static void RequestReceived(Request request) { // url comes in as /foo/bar/12345?style=255 // // /CONTROLLER/ACTION/ // // LIGHTING SAMPLE URL: /0/1/?r=255&amp;g=255&amp;b=255&amp;zone=EnumAsInt // /0/... 0 = NetduinoControllerType.Lighting var validResponse = false; try { Logger.WriteLine(&quot;Start: &quot; &#43; request.Url &#43; &quot; at &quot; &#43; DateTime.Now); var urlInParts = request.Url.TrimStart(UriPathSeparator).Split(new[] {'?'}, 2); string[] uriSubParts = null; stri https://channel9.msdn.com/coding4fun/articles/Project-Detroit-Lighting-System Mon, 21 May 2012 16:00:00 GMT https://channel9.msdn.com/coding4fun/articles/Project-Detroit-Lighting-System Brian Peek, Clint Rutkas, Dan Fernandez Brian Peek, Clint Rutkas, Dan Fernandez 4 https://channel9.msdn.com/coding4fun/articles/Project-Detroit-Lighting-System/RSS NETMF Project Detroit Project Detroit: An Overview In this article, we will give an overview of the technical side of Project Detroit, the Microsoft-West Coast Custom Mustang creation. If you're not already familiar with this project, you can find more information here Key Design Decisions It’s important to keep in mind that this car was built for a TV show with a set schedule. As a result, there are a number of unique design decisions that came into play. Generic Episode Image Schedule Working backwards, the reveal for the car was set for Monday November 28, 2011 at the Microsoft Store in Bellevue, Washington. We started the project in early August, which gave us approximately 12 weeks for research, development, vehicle assembly, and testing. This was by far the #1 design decision as any ideas or features for the car had to be implemented by the reveal date. Off the Shelf Parts Another key design decision was to, where possible, use off-the-shelf hardware and software in order to allow  interested developers to build and reuse some of the subsystems for their own car (at least the ones that don’t require welding). For example, instead of buying pricey custom sized displays for the instrument cluster or passenger display, we used stock Samsung Series 7 Slate PCs and had West Coast Customs do the hard work of building a custom dash to hold the PC.   Hardware and Networking The car is packed with a variety of computers and networking hardware. • Instrument Cluster Slate – This slate is on the driver's side and manages the instrument cluster application and the On-Board Diagnostic (OBD) connection to read telemetry data from the car. • Passenger Slate – This slate, which is built into the passenger's side, runs a custom Windows 8 application (see Passenger slate below). USA_ • Laptop 1 – This laptop runs the REST service to control different parts of the car, the Kinect socket service for the front Kinect, and the user message service to display messages on the rear glass while driving. • Laptop 2 – This laptop runs the Heads Up Display (HUD) service, the Kinect socket service for the back Kinect, the OBD-II database, and Azure services. • Windows Phone – A Nokia Lumia 800 connects via WiFi and a custom Windows Phone 7 application (See Windows Phone application below). • Xbox 360 – The Xbox 360 displays on either the passenger HUD or the rear glass display. • Networking – A NETGEAR N600/WNDR3700 wireless router provides wired and wireless access for everything in the car, which is used in conjunction with a Verizon USB network card plugged into a Cradle Point MBR900 to provide an always-on 3G/4G LTE internet connection. The slates, laptops, and Xbox 360 are connected via CAT5e cable, while the Windows Phone 7 connects via WiFi. Note: One of the limitations of the Kinect SDK is that if you have multiple Kinects plugged into one PC, only one of those Kinects can do skeletal tracking at a time (color/depth data works just fine). Because of this, we decided to have a dedicated laptop plugged into the front Kinect and another laptop plugged into the back Kinect in order to allow front and back skeletal tracking at the same time. If we'd not used simultaneous skeletal tracking, we could have combined all of the systems onto a single laptop. Architecture Here is a quick overview of the application architecture. detroitArch   REST Service Layer The REST Service Layer allowed different systems talk to one another. More importantly, it allowed different services to control hardware they normally wouldn't be able to access. 1. Thin client approach The solution we chose was to have all the services that control different parts of the car reside on the laptops and have client applications like the Windows Phone application send REST commands to execute an action so the service layer would execute the request. 2. REST-enable hardware Controlling hardware should be invisible to the consuming clients. For example, hardware that requires USB communication would be impossible to control with a Windows Phone. The service layer allowed us to control hardware in a way that was invisible to the end user. 3. Helper Libraries To simplify communication with the service layer, we built a set of helper classes to abstract out repetitive tasks like JSON serialization/deserialization, URI building, etc. For example, to get the list of car horn “ringtones”, the client application can call HornClient.List() to get back a list of available ringtone filenames. To set the car horn, the client calls HornClient.Set(filename), and to play the car horn, it then calls HornClient.Play(filename). The Helper libraries were built to work on Windows 7, Windows 8, and Windows Phone 7. OBD-II We have already released an article and library on the OBD-II portion of the car.  In short, OBD-II stands for On-Board Diagnostics. Hooking into this port allows one to query for different types of data from the car, which we use to get the current speed, RPMs, fuel level, etc. for display in the Instrument Cluster and other locations. OBD can do far more than this, but it's all we needed for our project. Please see the linked articles for further details on the OBD-II library itself. For the car, because only one application can open and communicate with a serial port at one time, we created a WCF service that polls the OBD-II data from the car and GPS data from a Microsoft Streets & Trips GPS locator, and returns it to any application that queries the service. For the OBD library, we used a manual connection to poll different values at different intervals. For values critical to driving the car—like RPM, speed, etc.—we polled for the values as quickly as the car could return them. With other values that weren’t critical to driving the car—like the fuel level, engine coolant temperature, etc.—we polled at a 1-2 second interval. For GPS, we subscribed to the LocationChanged event, which would fire when the GPS values changed. Rather than creating a new serial port connection for every WCF request for OBD data, we created a singleton service that is instantiated when the service first runs. Accordingly, there is only one object in the WCF service that represents the last OBD and GPS data returned, which is obtained by the continual reading of the latest OBD data using the OBD library as described above. This means that calls to the WCF service ReadMeasurement method didn’t actually compute anything, but instead serialized the last saved data and returned it via the WCF service. Since WCF supports multiple protocols, we implemented HTTP and TCP and ensured that any WCF service options we chose worked on Windows Phone, which, for example, can only use basic HTTP bindings. To enable the ability to change the programming model later and to simplify the polling of the service, we built a helper library for Windows and Windows Phone that abstracts all the WCF calls. The code below creates a new ObdService class and signs up for an event when the measurement has changed. The Start method does a couple of things: it lets you set the interval that you want to poll the ObdService, in this case every second (while the instrument cluster needs fast polling, the database logger can poll once a second). It also determines what IP address the service is hosted at (localhost), the protocol (HTTP or TCP), and whether to send “demo mode” data. Since one of the main ways the car is showcased is when it’s stopped on display, “demo mode” sends fake data, instead of always returning 0's for MPH, RPM, etc., so people can see what the instrument cluster would look like in action. _service = new ObdService(); _service.ObdMeasurementChanged += service_ObdMeasurementChanged; _service.Start(new TimeSpan(0, 0, 0, 0, 1000), localhost, Protocol.Http, false); void service_ObdMeasurementChanged(object sender, ObdMeasurementChangedEventArgs e) { Debug.Writeline("MPH=” + e.Measurement.MilesPerHour); } OBD-II Database & Azure Services To record and capture the car telemetry data like MPH, RPM, engine load, and throttle (accelerator) position, as well as location data (latitude, longitude, altitude, and course), we used a SQL Server Express database with a simple, flat Entity Framework model, shown below. The primary key, the ObdMeasurementID is a GUID that is returned via the ObdService.  Just like above, the database logger subscribes to the ObdMeasurementChanged event and receives a new reading at the time interval set in the Start() method. image The Windows Azure data model uses Azure Table Services instead of SQL Server. The data mapping is essentially the same since both have a flat schema. For Azure Table Storage, in addition to the schema above, you also need a partition key and a row key. For the partition key, we used a custom TripID (GUID) to represent a Trip. When the car is turned on/off a new TripID is created. That way we could group all measurements for that particular trip and do calculations based on that trip, like the average miles per gallon, distance traveled, fastest speed, etc. For the row key, we used a DateTimeOffset and a custom extension method, ToEndOfDays() that provides a unique numerical string (since Azure's row key is a string type) that subtracts the time from the DateTime.Max value. The result is that the earlier a DateTime value, the larger the number. Example: Time=5/11/2012 9:14:09 AM, EndOfDays=2520655479509478223 //larger Time=5/11/2012 9:14:11 AM, EndOfDays=2520655479482804811 //smaller Since they are ordered in reverse order, with the most recent date/time being the first row, we can write an efficient query to pull just the first row to get the current latitude/longitude without needing to scan the entire table for the last measurment. public override string RowKey { get { return new DateTimeOffset(TimeStamp).ToEndOfDays(); } set { //do nothing } } public static class DateTimeExtensions { public static string ToEndOfDays(this DateTimeOffset source) { TimeSpan timeUntilTheEnd = DateTimeOffset.MaxValue.Subtract(source); return timeUntilTheEnd.Ticks.ToString(); } public static DateTimeOffset FromEndOfDays(this String daysToEnd) { TimeSpan timeFromTheEnd = newTimeSpan(Int64.Parse(daysToEnd)); DateTimeOffset source = DateTimeOffset.MaxValue.Date.Subtract(timeFromTheEnd); return source; } } To upload data to Azure, we used a timer-based background uploader that would check to see if there was an internet connection, and then filter and upload all of the local SQL Express rows that had not been submitted to Azure using the Submitted boolean database field. On the Azure side, we used an ASP.NET MVC controller to submit data. The controller deserializes the data into a List<MeasurementForTransfer> type, it adds the data to a blob, and adds the blob to a queue as shown below. A worker role (or many) will then read items off the queue and the new OBD measurement rows are placed into Azure Table Storage. public ActionResult PostData() { try { StreamReader incomingData = new StreamReader(HttpContext.Request.InputStream); string data = incomingData.ReadToEnd(); JavaScriptSerializer oSerializer = new JavaScriptSerializer(); List<MeasurementForTransfer> measurements; measurements = oSerializer.Deserialize(data, typeof(List<MeasurementForTransfer>)) as List<MeasurementForTransfer>; if (measurements != null) { CloudBlob blob = _blob.UploadStringToIncoming(data); _queue.PushMessageToPostQueue(blob.Uri.ToString()); return new HttpStatusCodeResult(200); } ... } } Instrument Cluster Much of this is also covered in our previously released OBD-II library where the instrument cluster application is included as a sample. This is a WPF application that runs on a Windows 7 slate. It contains three different skins designed by 352 Media—a 2012 Mustang dashboard, a 1967 Mustang dashboard, and a Metro-style dashboard—each of which can be "swiped" through. This application queries the OBD-II WCF service described above as quickly as it can to retrieve speed, RPM, fuel level, and other data for display to the driver. The gauges are updated in real-time just as a real dashboard instrument cluster would behave. obd1obd2obd3 HUD The HUD (or Heads Up Display) application runs on one of the two Windows 7 computers in the car. This is a full-screen application that is output via a projector to a series of mirrors and a projection screen. This is then reflected onto the front glass of the windshield of the car. To install these, we altered the physical car's body and created brackets to mount mirrors and the projectors. In the picture on the left, you can see the dashboard's structural member pivoted outward. You can see the 12" section we removed and added in the base plate to allow light to be reflected through to the windshield. Bill Steele helped design and implement the physical HUD aspect into the car. alterationFrame mirrors The HUD application has several different modes.  The mode is selected from the Windows Phone application. • POI / Mapping – This uses Bing Maps services. The phone or Windows 8 passenger application can choose one of a select group of categories (Eat, Entertain, Shop, Gas). Once selected, the REST service layer is contacted and the current choice is persisted. The HUD is constantly polling the service to know what the current category is, and when it changes, the HUD switches to an overhead map display with the closest locations of that category displayed, along with your always updated current GPS position and direction. The list of closest items in the category is requested every few seconds from the Bing Maps API and the map is updated appropriately. image • Car telemetry - In the car telemetry mode, the OBD data from the WCF service described above is queried and displayed on the screen.  This can be though of as an overall car "status" display with the speed, RPMs, real-time MPG, time, and weather information. • Weather – We use the World Weather Online API to get weather data for display on the HUD. This API allows queries for weather based on a latitude and longitude, which we have at all times. A quick call to the service gives us the current temperature and a general weather forecast, which we display as an icon next to the temperature in the lower-left portion of the screen. image • Kinect – Using our Kinect Service, with the standard WPF client code, we can display the rear camera on the HUD to help the driver when backing up. See the Kinect Service project for more information on how this works and to use the service in an application of your own.   Windows Phone Application One of the main ways to control the vehicle is through the Windows Phone application.  a The first pivot of the app allows the user to lock, unlock, start the car, and set off the alarm.  This is done through the Viper product from Directed Electronics. a The second pivot contains the remaining ways that a user can interact with the car. • Kinect – This uses the Kinect service much in the way the HUD does. It can display both the front and rear cameras as well as allow the user to listen to an audio clip and send it up to the car while applying a voice changing effect. a • Voice Effect – When the Talk button is pressed, the user can record their voice via the microphone. When released, the audio data is packaged in a simple WAV file and uploaded to the REST service. The user can select from several voice effects, such as Chipmunk and Deep. On the service side, that WAV file is modified with the selected effect and then played through the PA system. The code in this section of the app is very similar to the Coding4Fun Skype Voice Changer. We use NAudio and several pre-made effects to process the WAV file for play. • Lighting – This controls the external lighting for the car. The user can select a zone, an animation, and a color to apply. Once selected, this is communicated through the REST service to the lighting controller. a • Messaging – This presents a list of known pictures and videos for the user. The selection is sent to the car through the REST service and displayed on the projector that is pointed at the rear window, allowing following drivers to see the image, video, or message.  • Point Of Interest – As described earlier, this is the way the user can turn on the Point of Interest map on the HUD.  Selecting one of the four items sends the selection to the REST service where it is persisted. The polling HUD will know when the selection is changed and display the map interface as shown above. • Telemetry – This is a replica of the instrument cluster that runs on the Windows 7 slate. OBD data is queried via the WCF service, just like the slate, and displayed on the gauges, just like the slate.  image • Projection Screen – This will raise and lower the projection screen on the rear of the car. • Horn – This displays a list of known horn sound effects that live on the REST service layer. Selecting any of the items will send a command through the REST to play that sound file on the external sound system of the car. This selected audio file would play when the horn was pressed in the car. • Settings – Internal settings for setting up hardware and software for the car. Passenger Application The passenger interface runs on a Samsung Series 7 slate running the Windows 8 Consumer Preview. This interface has a subset of the functionality provided by the Windows Phone application, but communicates through the same REST service. From this interface, the passenger can set the car horn sound effect, view the front and back Kinect cameras, select a Point of Interest category to be displayed on the HUD, and select the image, video or message that will be displayed on the rear window. image External Car Lighting The external lighting system was controlled by a web server running on a Netduino Plus using a Sparkfun protoshield board to simplify wiring, and allow for another shield to be used. The actual lights were Digital Addressable RGB LED w/ PWM. We'll also have a more in-depth article on this system on Coding4Fun shortly. The car is broken down into different zones—grill, wheels, vents, etc. It also has a bunch of pre-defined procedural animation patterns that have a few adjustable parameters that allow for things like a snake effect, a sensor sweep, or even a police pattern. Each zone has its own thread which provides the ability to have multiple animation patterns going at the same time. When a command is received, the color, pattern, zone, and other data is then processed. Here is a basic animation loop pattern. private static void RandomAnimationWorker() { var leds = GetLedsToIlluminate(); var dataCopy = _data; var r = new Random(); while (IsThreadSignaledToBeAlive(dataCopy.LightingZone)) { for (var i = 0; i < leds.Length; i++) SetLed(leds[i], r.Next(255), r.Next(255), r.Next(255)); LedRefresh(); Thread.Sleep(dataCopy.TickDuration); } } Rear Projection Window rearGlass The rear projection system consists of two 4” linear actuators, a linear actual controller, the NETMF web server from above, a Seeed Studio Relay Shield, the back glass of a 1967 Ford Mustang, some rear projection film, a low profile yet insanely bright projector that accepts serial port commands, and a standard USB to serial adapter. The REST service layer toggles the input of the projector based on the selected state.  This would allow us to go from the HDMI output of an Xbox 360 to the VGA output of the laptop.  While doing this, the REST layer sends a command to the NETMF web server to either raise or lower the actuators. Here is the code for the NETMF to control the raising and lowering the glass: public static class Relay { // code for for Electronic Brick Relay Shield static readonly OutputPort RaisePort = new OutputPort(Pins.GPIO_PIN_D5, false); static readonly OutputPort LowerPort = new OutputPort(Pins.GPIO_PIN_D4, false); const int OpenCloseDelay = 1000; public static bool Raise() { return ExecuteRelay(RaisePort); } public static bool Lower() { return ExecuteRelay(LowerPort); } private static bool ExecuteRelay(OutputPort port) { port.Write(true); Thread.Sleep(OpenCloseDelay); port.Write(false); return true; } } Messaging System This is a WPF application that leveraged the file system on the computer to communicate between the REST service layer and itself.  Visually, it shows the message/image/video in the rear view mirror but it actually does two other tasks, it operates our car horn system and plays the recorded audio output from the phone. • Displaying Messages To display images, we poll the REST service every second for an update.  Depending on the return type, we either display a TextBlock element or a MediaElement. • Detecting and Playing Car Horn When someone presses the horn in the car, it is detected by a Phidget 8/8/8 wired into a Digital Input. In-between the car horn and the Phidget, there is a relay as well. This isolates the voltage coming from the horn and solves a grounding issue. We then feed back two wires from that relay and put one into the ground and the other into one of the digital inputs. In the application, we listen to the InputChange event on the Phidget and play / stop the audio based on the state. • Detecting new recorded audio from the phone and car horn changes When someone talks into the phone or selects a new car horn, the REST service layer places that audio file into a predetermined directory. The Messaging service then uses a FileSystemWatcher to detect when this file is added. The difference between the car horn detection and recorded audio is the recorded audio will play once it is done writing to the file system. External PA System To interact with people, we installed an external audio PA or Public Address system. This system is hooked into the laptop that is connected to the car horn, and can play audio data from the phone. Having a PA system that is as simple as an audio jack that plugs into a PC enabled us to have different ringtones for the car horn and to talk through the car using Windows Phone. Conclusion After months of planning and building, the Project Detroit car was shown to the world on an episode of Inside West Coast Customs. Though it was a ton of work, the end product is something we are all proud of. We hope that this project inspires other developers to think outside the box and realize what can be done with some off-the-shelf hardware, software, and passion. splash ]]> https://channel9.msdn.com/coding4fun/articles/Project-Detroit-An-Overview In this article, we will give an overview of the technical side of Project Detroit, the Microsoft-West Coast Custom Mustang creation. If you're not already familiar with this project, you can find more information here. Key Design DecisionsIt’s important to keep in mind that this car was built for a TV show with a set schedule. As a result, there are a number of unique design decisions that came into play. ScheduleWorking backwards, the reveal for the car was set for Monday November 28, 2011 at the Microsoft Store in Bellevue, Washington. We started the project in early August, which gave us approximately 12 weeks for research, development, vehicle assembly, and testing. This was by far the #1 design decision as any ideas or features for the car had to be implemented by the reveal date. Off the Shelf PartsAnother key design decision was to, where possible, use off-the-shelf hardware and software in order to allow interested developers to build and reuse some of the subsystems for their own car (at least the ones that don’t require welding). For example, instead of buying pricey custom sized displays for the instrument cluster or passenger display, we used stock Samsung Series 7 Slate PCs and had West Coast Customs do the hard work of building a custom dash to hold the PC. Hardware and NetworkingThe car is packed with a variety of computers and networking hardware. Instrument Cluster Slate – This slate is on the driver's side and manages the instrument cluster application and the On-Board Diagnostic (OBD) connection to read telemetry data from the car.Passenger Slate – This slate, which is built into the passenger's side, runs a custom Windows 8 application (see Passenger slate below). Laptop 1 – This laptop runs the REST service to control different parts of the car, the Kinect socket service for the front Kinect, and the user message service to display messages on the rear glass while driving.Laptop 2 – This laptop runs the Heads Up Display (HUD) service, the https://channel9.msdn.com/coding4fun/articles/Project-Detroit-An-Overview Mon, 14 May 2012 16:00:00 GMT https://channel9.msdn.com/coding4fun/articles/Project-Detroit-An-Overview Brian Peek, Clint Rutkas, Dan Fernandez Brian Peek, Clint Rutkas, Dan Fernandez 11 https://channel9.msdn.com/coding4fun/articles/Project-Detroit-An-Overview/RSS Project Detroit
__label__pos
0.740996
Questions tagged [processor] The tag has no usage guidance. Filter by Sorted by Tagged with -2 votes 0 answers 37 views Intel Core i5-1240P vs Intel Core i7-1165G7 [closed] Refer: Intel Core i5-1240P vs Intel Core i7-1165G7 As I see that Intel Core i5-1240P outsmarts Intel Core i7-1165G7 in most of the benchmarks as shown in the above link. Can I conclude that it is ... 1 vote 0 answers 43 views Access register values from a PicoBlaze / MicroBlaze soft processor We are conducting research on the reliability of registers deployed in embedded RISC processors where the focus is to ensure the reliability of their contents during transient faults. To do this we ... • 1,154 10 votes 7 answers 2k views How do 16-bit addresses work inside 8-bit data bus processors? As a project I am building a small 8-bit RISC processor out of discrete ICs. I have 17 instructions and cannot fit all information into instructions that are only one byte, so I have been thinking ... • 1,154 1 vote 0 answers 16 views Can we calculate leakage power after synthesis at the architectural level power analysis itself? As I understand it, leakage power depends after implementation and not on the architectural level itself. When I report power after synthesis in Vivado I get even the leakage power. Is this possible ... 0 votes 1 answer 101 views Are FPGA and PC communications possible without a microprocessor i.e. do all FPGA dev boards have processors in? [closed] I am new to FPGA design. I have worked on a Zedboard, used AXI bus and developed IP. However, I am not clear on some of the basic things. I would like to learn the following questions. My sincerest ... • 13 0 votes 1 answer 421 views Why don't we see an MMU on a high-end MCU? In the past, microcontrollers were fairly simple and had poor performance, making the idea of running a full OS on them not viable. Today, there are multi-core MCUs running at over 500 MHz (e.g. ... 2 votes 1 answer 45 views Replacing a keypad on DYMO LetraTag I'm rebuilding my label printer to become an Internet service using an ESP8266. It's a fun project, never mind the usefulness. The keypad will be removed and instead my MCU emulates keypresses. The ... • 163 0 votes 1 answer 80 views 10gbase-kr autonegociation and ICs My goal is to propose building a 3U VPX card which connects to a backplane. After some research, the preferred connection between cards is over 10gbase-kr (although SGMII is supported in some ... 3 votes 2 answers 651 views maximum memory supported by processor - why often stated less than 1TB? I want to understand technical details of limitations of maximum memory size a system / processor can support. Below what I was able to find via web search to date Wiki: Modern 64-bit processors such ... 1 vote 0 answers 32 views Are coarse-grained reconfigurable architectures a subset of dataflow architecture? By definition, dataflow architectures consist of large modules in the dataflow path, such as adders and multipliers for integer, floating-point, or fixed-point computation. Hence, are coarse-grained ... -3 votes 2 answers 164 views Why Intel does not make 5nm chips buying UV machines from ASML? [closed] I've recently found out (correct me if I'm wrong here), that 5nm lithograthy machines are made by ASML, which is independent and Intel invested in it. I've tried web searches but I still do not ... 0 votes 2 answers 49 views How many instructions can a vector processor issue per cycle? [closed] I currently have vector processors in class and wondered whether a vector processor only issues one (vector) instruction per cycle (in order processor). Maybe this question is stupid and it depends ... • 105 -1 votes 2 answers 140 views What are the factors that determine the clock speed of a processor? What are the factors that determine the clock speed of a processor? Since the speed of electricity is the same for all processors then I assume that how fast the binary data is transmitted to ... • 109 0 votes 4 answers 163 views Question about PID control loop timing For my project I am creating a RISC processing architecture on an FPGA that can perform various basic instructions like adding, multiplying, subtracting, storing and fetching from memory etc. To prove ... • 1,154 1 vote 1 answer 795 views Help in understanding Store Word (SW) instruction in Risc-V So this is what I understood from what my professor said, but I don't think it's the right answer. What am I doing wrong? I'm sure It's just some small thing that I'm getting mixed up. Given ... 0 votes 2 answers 63 views What is throughput as far as processors are concerned? My teacher showed some algothrims, RR, FCFS and others. In the end he exposed a table with throughput of the algorithms. He explained what thoughput is but he failed miserably. He first said that ... 1 vote 1 answer 693 views How can I modify single-cycle MIPS processor to implement jal command? Hello Stack exchange community I was wondering which modification should I have to make in order to enable single-cycle MIPS processor to run a jal(jump and link) command? My most pressing confusion ... • 11 0 votes 1 answer 69 views Number of read and write ports on L2 and L3 cache I have an Intel Core i9-9900K processor (some specs here) and I'm trying to figure out how many read and write ports each level of cache has, for a personal project. I cannot find this in any online ... 0 votes 2 answers 82 views How are transistors on processor chips designed to withstand high operating temperatures? The process for transistors grow smaller every few years, and operating temperatures reach around 100 degree Celsius. This makes one wonder as to how these tiny designs are able to hold up within ... 0 votes 0 answers 113 views What processor architecture is in a 230GMULps KPU design? While AI products are becoming popular recently, when looking at the "Seeed Studio Grove AI HAT for Edge Computing Artificial Intelligence Board" it mentions a RISC-V, a 230GMULps 16-bit KPU ... • 515 1 vote 1 answer 73 views confusion understanding a processor? As shown highlighted in attached photo,In case of 6713 dsp,during each clock cycle, up to eight instructions can be carried out in parallel Does this happen in case of every processor that multiple ... • 791 0 votes 1 answer 144 views Single Cycle Data-path Requirements How having separate instruction and data memories helps in implementing a single cycle data-path for mips instruction set? i want to know why we can only use data-path element once in a cycle for ... 1 vote 3 answers 931 views Effect of doubling clock frequency on computer performance If we double the clock frequency of a CPU, does that translate to a doubling of the CPU performance? Assuming that the number of instructions and CPI are constant, we have an inverse relationship ... • 143 14 votes 4 answers 7k views Where are registers and what do they look like? I racked my brain through my comp-arch class and reread wiki’s article on hardware registers (they’re flip-flops, I get that), but one year later and I still don’t understand what a register ... 0 votes 0 answers 34 views Does stage Sy of instruction have to wait till all earlier instructions has executed their corresponding stage I am trying to understand execution of instruction in RISC pipeline. Can stage Sy of instruction I2 execute before stage Sy of I1? That is, in below example, will it be allowed to run I2's ID in C3 as ... • 227 1 vote 2 answers 116 views How do I procure SoCs in small quantities? [closed] I want to design an SBC but I am having difficulty with buying the SoC. I'm thinking of Snapdragon, Mediatek, Allwinner, Amlogic and Rockchip (These are the ones I know, if you know others I would ... 1 vote 4 answers 219 views royalty free embedded processor [closed] I got into FPGA design last year for a project, and had some success with a Xilinx Spartan 6 dev board using ISE. I could do everything with this low cost board and ISE 14, which is free. I needed an ... • 5,367 0 votes 2 answers 452 views Data Bus and High Impedance Let's consider an interface between a simple microprocessor and a certain memory. For instance, let's assume that the microprocessor drives the address bus, a read signal, a write signal, and that the ... • 3,278 0 votes 2 answers 109 views Need a processor to be able to turn off its own power I have a processor that is powered by a mains 5V power from a wall adapter, and has a short term battery backup. I need the processor to turn on automatically and immediately when 5V mains supply is ... • 167 -1 votes 2 answers 65 views Data transfer from/to memory [closed] Consider an interface (between a memory and a processor, or between a memory and an ASIC, or similar situations) in which there is a data bus of 8 bit. Suppose I want read a 16 bit data from memory, ... • 3,278 1 vote 1 answer 1k views Understanding branch delay slot and branch prediction prefetch in instruction pipelining Let me define: Branch delay slot: Typically assemblers reorder instructions to move some instructions immediately after branch instruction, such that the moved instruction will always be executed, ... • 227 1 vote 0 answers 29 views Finding percentage memory utilization in pipelining architecture I was solving problems from the exercise of the book "Computer Organization and Design" by Patterson. The problem reads like this: Consider stage latencies: ... • 227 0 votes 1 answer 392 views Why cant we increase chip area? According to Moore's law, transistors are getting double every 24 months. But now, we have reached the transistor size limit which results in leakage current. Then why can't we increase chip area size,... • 101 3 votes 2 answers 3k views How many stall cycles resulted by incorrectly predicted branch in instruction pipelining I have been solving following exercise problem from book Computer Organization by Patterson and Hennessy: The importance of having a good branch predictor depends on how often conditional branches ... • 227 0 votes 2 answers 53 views Have separate instructions for each register or pass register as argument? I am trying to design a (very) simple processor architecture. I am in the process of creating a basic instruction set for it, however I am not sure of the best ("best" meaning what most people use - ... • 145 1 vote 1 answer 86 views Analog Blackfin Processor Silicon Revision issue [closed] Recently we got a large batch of ADSP-BF5346s that say they are Silicon Rev 3 but internally read as Rev 2. Is there a way for me to determine the Silicon Revision number on the rest of the shipment ... • 13 0 votes 1 answer 2k views Verilog) Multi-source in Unit <> on signal <>; this signal is connected to multiple drivers Hi I'm trying to design a multiprocessor in Verilog. ... • 113 5 votes 1 answer 1k views Inside a CPU, what happens in a single clock cycle? In grossly simplified terms, a processor calculates 1 instruction in a single clock cycle. But what does that even mean? If a processor is a bunch of transistors, is 1 clock cycle simply 1 state ... 9 votes 5 answers 4k views In a CPU, does the speed of a calculation affect the heat generated? Take as an example a CPU that is capable of changing its clock speed, like a modern computer CPU (Intel, AMD, whatever). When it does a certain calculation at a particular clock speed, does it ... 1 vote 3 answers 483 views Computer architecture why is MemRead used? Why is a control signal MemRead needed for the Data Memory element if whenever the output Read Data is not desired it will be multiplexed out via MemtoReg? Wouldn't having MemRead always enabled ... • 11 0 votes 1 answer 276 views What is the best way to implement spi using 8085? [closed] I have to make a compass using 8085. I have to take serial data from magnetometer of mpu9250. Should i prefer bit banging to implement spi or make parallel out and parallel in hardware using shift ... 3 votes 1 answer 158 views Finding specifications for digital signal processors (DSPs) for given audio application [closed] I'm finding difficulties choosing an adequate processor solution for my application from my null experience with DSP: 8ch 24-bit @11025Hz I2S TDM Input Beamforming + ASNR MSS Multi-source selection ... 0 votes 1 answer 96 views Is a hardware register the same as a processor register? I have tried searching for the difference between these two terms but everything I find gives ambiguous results. What is the difference between a harware register and a processor register, if there is ... 0 votes 1 answer 48 views Lpc 43s50FET256 processor and its connections ı want to buy a nxp LPC43S50FET256 processor and ı made some research but I dont know whether lpc43s50 has already got bridge connections, ı also dont know for example whether ethernet is already ... user avatar -1 votes 1 answer 312 views Finding percentage accuracy of instruction pipeline branch predictor I need help in understanding the solution from solution manual. The question is from the exercise 4.24.4 and 4.24.5 of chapter 4 in the book Computer Organization and Design by Patterson and Hannessey ... • 129 1 vote 1 answer 432 views Understanding execution of sequence of pipeline instructions I need help in understanding the solution from solution manual. The question is from the exercise 4.22.2 of chapter 4 in the book Computer Organization and Design by Patterson and Hannessey (4th ... • 129 0 votes 1 answer 230 views Understanding instruction branching I need help in understanding the solution from solution manual. The question is from the exercise 4.22.1 of chapter 4 in the book Computer Organization and Design by Patterson and Hannessey (4th ... • 129 0 votes 2 answers 165 views Methods to detect errors in cache Are there methods apart from ECC, to detect and possibly correct cache errors? 0 votes 0 answers 553 views Understanding instruction pipelining speedup calculation I was solving the exercise problem 4.17.6 of chapter 4 in the book Computer Organization and Design by Patterson and Hannessey (4th edition): Percentage occurrences of the instructions are as ... • 129 0 votes 1 answer 706 views Understanding processor instruction pipeline problem solution I need help in understanding the solution from solution manual. The question is from the exercise 4.13.5 of chapter 4 in the book Computer Organization and Design by Patterson and Hannessey (4th ... • 129  
__label__pos
0.652252
ggheat2: ggheat2 Description Usage Arguments Details See Also Examples View source: R/ggplots.R Description Function to plot a heat map using ggplot. Usage 1 2 3 4 5 ggheat2(data, corr = cor(data, use = "pairwise.complete"), cluster = TRUE, nbreaks = NULL, palette = if (is.null(nbreaks)) c("blue", "white", "red") else 1, legend_name = expression(rho), pch, cex = c(2, 6), label = FALSE, label_alpha = FALSE, label_color = "black", label_digits = 2, midpoint = 0, clim = c(-1, 1), ...) Arguments data a data frame or matrix (observations x variables) of numeric values corr a correlation matrix cluster logical or function; if TRUE, the variables will be clustered and reordered; if FALSE, no reordering will be done; otherwise, a custom clustering function may be given; see details nbreaks number of breaks to categorize the correlations (default is NULL, ie, a continuous scale) palette for a continuous scale, a vector of length three giving the low, mid, and high colors of the gradient (default is c('blue','white',''red), see scale_colour_gradient2); for a discrete scale, a character string of the palette name or an integer giving the index of the palette, see scale_colour_brewer legend_name the legend name; see discrete_scale pch (optional) plotting character; if missing, geom_tile is used instead of plotting characters cex size of pch; a vector of length one (all pch will be the same size) or two (size will be proportional to the correlation); default is c(2,6); seescale_size_identity label logical; if TRUE, adds correlation coefficients on top of each pch label_alpha logical, if TRUE, adds alpha transparency when label is TRUE (correlations closer to 0 will be less visible) label_color color of correlations (default is 'black') label_digits number of digits in correlation labels midpoint the midpoint value for continuous scaling of correlations (default is 0) clim vector of length two giving the limits of correlation coefficients (default is -1,1) ... additional arguments passed to geom_text for the diagonal labels Details Default cluster method is stats::hclust(dist(x), method = 'average') which will return a list containing a named vector, "order", which is used to reorder the variables. In order to pass a custom clustering function to cluster, the function must take a single input (a correlation matrix) and return either a vector or a list with a named vector, "order". See Also cor, ggheat, icorr, corrplot, https://github.com/briatte/ggcorr Examples 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 library('ggplot2') ggheat2(mtcars) ggheat2(mtcars, label = TRUE, label_alpha = TRUE, cluster = FALSE, ## additional args passed to diagonal labels colour = 'red', angle = 45, size = 7) ggheat2(mtcars, pch = 19, nbreaks = 6, cex = c(2,10), palette = 'PuOr', ## colorblind palette size = 5, hjust = 0.75) + ## passed to diag text labs(title = 'Correlation Matrix') ## custom clustering function ggheat2(data = NULL, corr = cor(mtcars, use = 'pairwise'), nbreaks = 5, palette = 'Blues', cluster = function(...) sample(ncol(mtcars))) raredd/plotr documentation built on Nov. 13, 2018, 7:05 a.m.
__label__pos
0.788893
Skip to content Related Articles Get the best out of our app GeeksforGeeks App Open App geeksforgeeks Browser Continue Related Articles Custom Excel Number Format Improve Article Save Article Like Article Improve Article Save Article Like Article MS Excel is a very important tool for businesses as well as for individuals with very useful features and tools. It is a market leader in spreadsheet editing and managing software. MS Excel contains many inbuilt number formats that can be used as per the needs of the user, however, sometimes users may need specific custom number formats that are not available in Excel by default. Custom Excel Number Format For example, if we want to round a decimal number to one digit after the decimal point, if we consider the number 44.64  we can use the custom number format ##.# to convert it to 44.6. If you want to represent number 347523450 using the Indian number system, of crores, lakhs, and thousands you can use the custom number format ##\,##\,##\,### to convert it to 34,75,23,450. First, let’s consider the list of the following numbers given below : Dataset   To Convert these numbers into our required format we have to execute the following steps: Step 1: Drag and select the numbers whose format has to be changed using the cursor. Dataset   Step 2: a) Go to home and click on format. Clicking-format-from-home   b) Then click on Format Cells. Clicking-format-cells   Or a) Right-Click and choose Format Cells. Clicking-format-cells   Format Cells Dialog Box appears. Editing-format-cells   Step 3: Choose a custom option from the given Dialog Box. Choosing-custom-option   Step 4: Double-Click on the Type box and erase the given format and type your required format as shown and press ok to convert the given number into your required format. Converting-number-into-format   Step 5: The numbers change to the required format. Numbers-changed-into-format   This is the way in which numbers can be changed to any custom format. However, if you would want to remove the custom formatting from your numbers you can follow the given steps: Step 1: Follow Step 1, Step 2, and Step 3 mentioned above in the article to go to Format Cells, Custom Format Tab as shown below: Clicking-on-custom-format   Step 2: Erase the format present in the custom dialog box and keep it blank and click on ok. Erasing-format   Step 3: The number format changes to the original. Numbers-changed-to-original   My Personal Notes arrow_drop_up Last Updated : 04 Dec, 2022 Like Article Save Article Similar Reads Related Tutorials
__label__pos
0.959439
Documentation Home MySQL PHP API Download this Manual PDF (US Ltr) - 2.4Mb PDF (A4) - 2.4Mb HTML Download (TGZ) - 247.5Kb HTML Download (Zip) - 255.2Kb MySQL PHP API  /  ...  /  mysqli_result::$num_rows, mysqli_num_rows 3.11.15 mysqli_result::$num_rows, mysqli_num_rows Copyright 1997-2020 the PHP Documentation Group. • mysqli_result::$num_rows mysqli_num_rows Gets the number of rows in a result Description Object oriented style int mysqli_result->num_rows ; Procedural style int mysqli_num_rows(mysqli_result result); Returns the number of rows in the result set. The behaviour of mysqli_num_rows depends on whether buffered or unbuffered result sets are being used. For unbuffered result sets, mysqli_num_rows will not return the correct number of rows until all the rows in the result have been retrieved. Parameters result Procedural style only: A result set identifier returned by mysqli_query, mysqli_store_result or mysqli_use_result. Return Values Returns number of rows in the result set. Note If the number of rows is greater than PHP_INT_MAX, the number will be returned as a string. Examples Example 3.127 Object oriented style <?php $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } if ($result = $mysqli->query("SELECT Code, Name FROM Country ORDER BY Name")) { /* determine number of rows result set */ $row_cnt = $result->num_rows; printf("Result set has %d rows.\n", $row_cnt); /* close result set */ $result->close(); } /* close connection */ $mysqli->close(); ?> Example 3.128 Procedural style <?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } if ($result = mysqli_query($link, "SELECT Code, Name FROM Country ORDER BY Name")) { /* determine number of rows result set */ $row_cnt = mysqli_num_rows($result); printf("Result set has %d rows.\n", $row_cnt); /* close result set */ mysqli_free_result($result); } /* close connection */ mysqli_close($link); ?> The above examples will output: Result set has 239 rows. See Also mysqli_affected_rows mysqli_store_result mysqli_use_result mysqli_query
__label__pos
0.956255
Verbal Reasoning - Cube and Cuboid Intrducion: • In a cube or a cuboid there are six faces in each. • In a cube length, breadth and height are same while in cuboid these are different. • In a cube the number of unit cubes = (side)3. • In cuboid the number of unit cube = (l x b x h). Example: A cube of each side 4 cm, has been painted black, red and green on pars of opposite faces. It is then cut into small cubes of each side 1 cm. The following questions and answers are based on the information give above: 1. How many small cubes will be there ? Total no. of cubes = (sides)3 = (4)3 = 64 2. How many small cubes will have three faces painted ? From the figure it is clear that the small cube having three faces coloured are situated at the corners of the big cube because at these corners only three faces of the big cube meet. Therefore the required number of such cubes is always 8, because there are 8 corners. 3. How many small cubes will have only two faces painted ? From the figure it is clear that to each edge of the big cube 4 small cubes are connected and two out of them are situated at the corners of the big cube which have all three faces painted. Thus, to edge two small cubes are left which have two faces painted. As the total no. of edges in a cube are 12. Hence the no. of small cubes with two faces coloured = 12 x 2 = 24 (or) No. of small cubes with two faces coloured = (x - 2) x No. of edges where x = (side of big cube / side of small cube) 4. How many small cubes will have only one face painted ? The cubes which are painted on one face only are the cubes at the centre of each face of the big cube. Since there are 6 faces in the big cube and each of the face of big cube there will be four small cubes. Hence, in all there will be 6 x 4 = 24 such small cubes (or) (x - 2)2 x 6. 5. How many small cubes will have no faces painted ? No. of small cubes will have no faces painted = No. of such small cubes = (x - 2)3 [ Here x = (4/1) = 4 ] = (4 - 2)3 = 8. 6. How many small cubes will have only two faces painted in black and green and all other faces unpainted ? There are 4 small cubes in layer II and 4 small cubes in layer III which have two faces painted green and black. Required no. of such small cubes = 4 + 4 = 8. 7. How many small cubes will have only two faces painted green and red ? No. of small cubes having two faces painted green and red = 4 + 4 = 8. 8. How many small cubes will have only two faces painted black and red ? No. of small cubes having two faces painted black and red = 4 + 4 = 8. 9. How many small cubes will have only black painted ? No. of small cubes having only black paint. There will be 8 small cubes which have only black paint. Four cubes will be form one side and 4 from the opposite side. 10. How many small cubes will be only red painted ? No. of small cubes having only red paint = 4 + 4 = 8. 11. How many small cubes will be only green painted ? No. of small cubes having only green paint = 4 + 4 = 8. 12. How many small cubes will have at least one face painted ? No. of small cubes having at least one face painted = No. of small cubes having 1 face painted + 2 faces painted + 3 faces painted = 24 + 24 + 8 = 56. 13. How many small cubes will have at least two faces painted ? No. of small cubes having at least two faces painted = No. of small cubes having two faces painted + 3 faces painted = 24 + 8 = 32.
__label__pos
1
Learn Python With Dhawal -5- Chapter CHAPTER 5 In this chapter we are going to learn more about Loops in python and how to use them in various case scenarios. Loops in any programming language are contextually the same, as in they are a set of instructions as we say technically or a particular lines of code in layman terms, which get executed again and again. Now, each loop has 3 main parts like variables. Loop has a declaration statement, conditional statement and an incremental factor. Since python takes off much of the programming load from the programmer and just allows us to code as if like we are playing, here we don't have to worry about the loops and their three sections for the most part but to understand how it works and how to use them we need to know the concept behind the loop. There are basically two types of loops. (1) Entry Guarded Loop and (2) Exit guarded Loops. Obviously these aren't actual terminologies but rather conceptual terms used to understand then working of the loops. Technically they're called the control statements or entry conditions. Hence the technical terms are Entry and Exit Controlled Loops. A set of statements which are repeatedly executed to do a certain task is called a loop. Traditionally loops are defined within the parenthesis but just like conditional statements where the bracket system is replaced with indentations, in loops too you no longer need brackets to define what's in the loop and what's out of it. There are 3 very important and basic loops. 1. WHILE Loop 2. DO....WHILE Loop 3. FOR Loop WHILE Loop WHILE Loop is an entry guarded loop, which means it first checks the condition, then allows the execution pointer to enter inside and start executing the statements. Once the statements are over the execution pointer moves back to the beginning of the loop and checks the condition, if it is true the same process repeats until the guarding condition becomes false and then the execution pointer is headed out of the loop towards the next statement. In this loop you need to be careful to alter the condition once the execution of the loop begins as, if you don't make the entry condition false after your work is done, it can run till infinity and will give you a run-time error. Syntax : Statement xyz1 while ( condition that I want to check): <tab>loop statement 1 <tab>loop statement 2 <tab>loop statement 3 <tab>loop statement 4 Statement xyz2 DO....WHILE Loop In python we don't have a DO...WHILE loop but it's actually necessary to know the concept of how it works. In a DO....WHILE LOOP, its an EXIT CONTROLLED LOOP, which means it checks the condition that is used to run a loop at the end of the loop statements. This means whether the condition is true or false, the loop will at least run once and give some output. This comes out as quite useful in its own case scenarios where you need some default output even if a condition is false. Syntax(non python pseudocode): DO{ <tab>loop statement <tab>loop statement <tab>loop statement <tab>loop statement <tab>loop statement }WHILE( the condition I want to check) FOR Loop It is one of the most used or I can say overused loops in every programming language ever. A for loop has proper three statements but all in one single line, The initiation, the control and the incremental statement. FOR Loop is also an entry controlled loop which means first there's intialistion then the condition is checked and then after executing the loop the increment is been made. There's a special type of this loop which we would use more than often in our coding tutorials further but you need to learn how the for loop functions before we actually start on using the shortcuts. Python's 'for' loop is more like 'for each' loop of other languages. Syntax(Non-Python Psuedocode): FOR( Initialisation, Condition, Increment ){ <tab>loop statement 1 <tab>loop statement 2 <tab>loop statement 3 <tab>loop statement 4 } Syntax (Python): Statement xyz1 FOR any variable name that I want in range (starting point, Ending point, step): <tab>loop statement 1 <tab>loop statement 2 <tab>loop statement 3 <tab>loop statement 4 Statement xyz2 FOR ENHANCE LOOP This is a special type of loop in Java but in python it is somehow used as your average for loop, where you don't have to specify anything but just the data or thing you want to run the for loop for. It'll decide everything else on its own. Syntax: Statement xyz1 FOR any variable name that I want in any other variable that I want to run it on : <tab>loop statement 1 <tab>loop statement 2 <tab>loop statement 3 Statement xyz2 Now, we will learn more about it using the examples. Code 1: Input : 1. counter=10; 2. while (counter >0 ): 3.     print ('The counter is: ',counter) 4.     counter=counter-1 Output: 1. The counter is:  10 2. The counter is:  9 3. The counter is:  8 4. The counter is:  7 5. The counter is:  6 6. The counter is:  5 7. The counter is:  4 8. The counter is:  3 9. The counter is:  2 10. The counter is:  1 Here as you can see, we had a variable named counter which had an initial value of 10, I wanted to print a countdown till one hence I made a condition that counter should be greater than 0 hence the loop was executed until the value of the counter became 0. If you notice I was decreasing the value of counter by one each time. Programming follows the RHS to LHS approach in general which means that in statement 4, first it decreased the value of counter by 1 as mentioned and then assigned the new value to the counter variable. Input : 1. counter=10; 2. while (counter >=0 ): 3.     print ('The counter is: ',counter) 4.     counter-=1 Output: 1. The counter is:  10 2. The counter is:  9 3. The counter is:  8 4. The counter is:  7 5. The counter is:  6 6. The counter is:  5 7. The counter is:  4 8. The counter is:  3 9. The counter is:  2 10. The counter is:  1 11. The counter is:  0 Here, as you can see it's pretty much the same code but I changed a few lines here. The condition that I checked was less than and equal to zero which meant that now the countdown will be printed till zero. Also, the decrement statement I used a shorthand operator, usually shorthand operators are like  ++,--, in other programming languages but in python we don't have them, instead we have += and -= where we have to specify the increment or the decrement value. Since here the value is 1 it will decrease by 1, you can try out the same code by making the incremental factor 2 and reversing the countdown by printing it from 0-10 instead of 10-0. I'd like to see if you can do that or not. Code 2: Input : 1. for counter in range (0,10): 2.     print ('The counter is: ',counter) Output: 1. The counter is:  0 2. The counter is:  1 3. The counter is:  2 4. The counter is:  3 5. The counter is:  4 6. The counter is:  5 7. The counter is:  6 8. The counter is:  7 9. The counter is:  8 10. The counter is:  9 As you can see here in the code above, we just printed a simply using 2 lines of code where the while took close to 4 and above to print the very same thing. This is the power of simplicity and ease that you get with python. Here, the counter variable has a starting value of 0 and ending value of 10 so the loop is run and the value of counter is incremented until it gets at 10, once it gets 10 the loop is terminated hence you'd get to see statements only from 0 to 10, if you want to print from 1 to 10 then you can use the range (1,11) to get the output. If you want to reverse then you can use the range (11,1) or range(10,0) or range (11,0). Try out your own examples of loops and ranges and see how it fairs out with you. Input: 1. for counter in range (2,22,2): 2.     print ('The counter is: ',counter) Output: 1. The counter is:  2 2. The counter is:  4 3. The counter is:  6 4. The counter is:  8 5. The counter is:  10 6. The counter is:  12 7. The counter is:  14 8. The counter is:  16 9. The counter is:  18 10. The counter is:  20 Here as you can see we kinda printed the table of two. Here in the range bracket we also specified the step aka the incremental factor. Here the incremental factor was +2 hence it increased the value of counter with 2 every time the loop was run. You can also make it -2 if you want to get it in the negative running from 20-2. This is how you use your usual for loops and use it to do various things. Code 3: Input : 1. fruitBasket={'apple', 'banana','mango','chikoo','guava'} 2. for fruit in fruitBasket: 3.     print ('The fruit is: ',fruit) Output: 1. The fruit is:  chikoo 2. The fruit is:  apple 3. The fruit is:  mango 4. The fruit is:  banana 5. The fruit is:  guava Here as you can see we didn't actually had to specify anything about the range or the size of the list here but still the for loop worked and printed every fruit name we had in out fruit basket list. This is usually known as the for enhance loop in other languages but here in python it's just your average for loop. I hope you try out some more examples on your own and play around with it to see how it works and what all it can take. You can use tuples instead of lists, you can use dictionary and others. Play with it yourself and find out more about it. Note : If you are someone who is been following this course, please comment your names down below and if possible do subscribe to website for more updates, I just write more than one subject and cover a lot of areas which you might also get interested to know upon. If there's significant amount of people commenting on this post with their email and name I would surely try to make and upload a sort of course notebook with more deeper examples and things which you'd only get to learn in actual engineering classrooms. But I can do that only when the response is good, also, please comment your doubts or things that you want to know so I can cover it in the next chapters. In Next chapter we will learn about nested loops and learn more about using them. << PREVIOUS CHAPTER || NEXT CHAPTER >>  --INDEX-- ~*~*~*~ This series is totally authored by me (Dhawal Joshi). Any similarities found on the text, or codes or anything is purely accidental. All the sources of reference will be mentioned, linked and will be given the proper credits. If I miss anything or there's anything wrong, feel free to comment or send me an email and I'll try to edit it out. I am not a Python expert, I am sharing whatever I have learnt on my own and with a few sources around to refer from which will be mentioned. Also feel free to share this series with others so most can benefit out of it. ~*~*~*~ Do comment and share your thoughts about it! I'd love to know what do you think. Also, I'd keep updating it quite often so do follow the Website to get all the updates by clicking here. Also, a minor headsup.... Obsessed is free to read on Kindle Unlimited! Do check it out. I'd be glad to read your reviews! Share : Are you getting regular fresh content updates? If not click on the button below. 0 comments: Post a Comment Do comment and share your thoughts.
__label__pos
0.986444
Share on facebook Share on twitter Share on linkedin Share on whatsapp xnegra.png API Testing Tutorial: A Complete Guide For Beginners Definition API stands for Application Programming Interface. It is a collection of functions, procedures, or methods that are available to be executed by other software applications. Its main purpose is to offer access to certain services and provide communication between software components. They make life easier for developers as they can take advantage of the functionality of an API, thus avoiding having to reprogram such functionality from scratch. An API endpoint is the destination of the API requested by the owner of a website. If a content management system (CMS) requests access to an API, the CMS serves as the API endpoint. It is important that websites function well so that they can become secure and supportive endpoints for developers who want to share their data. What is an API call? It´s also known as an API request, is the time when a website owner “calls” to use a developer’s API. “Saving the API”, “logins on the developer’s website” and “queries about the application” count as API calls. With this in mind, an API call limit is the number of times that you can request information about an API from a web service within a certain period of time. What are the testing phases for APi's As with tests to evaluate any other type of software, the typical phases are as follows: Api Definition We must consider the following items as the basis for designing test cases: Execution and evaluation of results For its execution and verification of results, we must take into account the behavior of the results: Pagination Does the API return a list? What is the size of the list? Does it support paging? Does it have a default paging size? Can I control the number of results I get on each page? Could it be different for each user? How does the API obtain this information for the user? Are there any restrictions for different API consumers, such as web, mobile or tablet? Authentication Who can access this API? How are they authenticated? How is authentication maintained for subsequent calls? How long does authentication remain valid? What is the risk of someone gaining unauthorized access? Query parameters / strings How are we sending data in the query string? What information is mandatory? What is optional? Are you validating it? Is it valid for Null types? What defines that the values are correct? What if those values change? Do I have to escape certain characters? Negative condition Are you returning the correct error codes? Are you giving the correct HTTP codes? Is the entry validated? Does it handle missing parameters? Handling wrong inputs? Is the appropriate error issued if the content type is wrongly requested? Are users blocked after issuing the same type of errors? Are there asynchronous calls – If yes, what if there is an error in that? Are these errors logged? What if the whole system or some part of the system is not available, how would it affect the user? What if the system crash during the transaction, how could it recover?  What error should I give? It should be remembered that one of the important characteristics of the external quality of the software that is intended to be tested in the API’s is interoperability, that is, “the ability of two or more systems or software components to exchange information and use the information exchanged. How can I run the tests?  For calls to an API, the Postman tool can be used. About the Author Laura Vitelli is a Senior QA Engineer, with 18 years of professional experience in the market, both locally and internationally. Don't forget to share this post! Share on facebook Share on google Share on twitter Share on linkedin Share on whatsapp Share on print SAN DIEGO 6790 Embarcadero Lane Suite 100 Carlsbad, CA 92011, USA +1 (888) 622-7098 MIAMI 1951 NW 7th Ave #600 Miami, FL 33136, USA +1 (888) 622-7098 CÓRDOBA Velez Sarsfield 576 Cordoba, Argentina X5000CCD +54 (351) 426-5110 LIMA Jiron Colina 107 Barranco, Lima CP 04, perÚ +51 (1) 248-8687 MEDELLÍN Calle 29 #41 – 105 Edificio Soho El Poblado, Medellin COLOMBIA +57 (4) 403-1770 ©Santex 2019. All rights reserved.
__label__pos
0.815445
Skip to content HTTPS clone URL Subversion checkout URL You can clone with HTTPS or Subversion. Download ZIP Fetching contributors… Cannot retrieve contributors at this time 72 lines (62 sloc) 1.65 kb require 'test/unit' require 'veewee' class TestVeeweeBuild < Test::Unit::TestCase def setup definition_dir=File.expand_path(File.join(File.dirname(__FILE__),"definitions")) #ENV['VEEWEE_LOG']="STDOUT" @ve=Veewee::Environment.new({ :definition_dir => definition_dir }) @definition_name="test_definition" @[email protected][@definition_name] @box_name=@definition_name @vd.postinstall_files=["_test_me.sh"] @[email protected]["virtualbox"].get_box(@box_name) end # First build of box # - the creation # - kickstart fetch # - postinstall execution def test_box_1_build assert_nothing_raised { #@box.build({"auto" => true,:force => true, #:nogui => true }) @box.build({"auto" => true,"force" => true }) } end # Run an ssh command def test_box_2_ssh assert_nothing_raised { [email protected]("who am i") assert_match(/root/,result.stdout) } end # Type on console def test_box_3_console_type assert_nothing_raised { @box.console_type(['echo "bla" > console.txt<Enter>']) [email protected]("cat console.txt") assert_match(/bla/,result.stdout) } end # Try shutdown def test_box_4_shutdown assert_nothing_raised { @box.halt } end # Now try build again (with no force flag) def test_box_5_build assert_raise(Veewee::Error) { @box.build({"auto" => true}) #@box.build({"auto" => true,:force => true, :nogui => true }) } end def test_box_6_destroy assert_nothing_raised { @box.destroy } end # # def teardown # #@ve.destroy(@vm_name,@vd) # # end end Jump to Line Something went wrong with that request. Please try again.
__label__pos
0.854338
Sign up × Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free. I have implemented an addressbook, I don't know what I do wrong, but whenever I select an address my whole app crashes and i receive the error > 2010-10-21 11:57:13.922 ANWB[2989:207] > *** Terminating app due to uncaught exception 'NSRangeException', reason: > '*** -[NSCFArray objectAtIndex:]: > index (0) beyond bounds (0)' > 2010-10-21 11:57:13.935 ANWB[2989:207] > Stack: ( > 843263261, > 825818644, > 842812211, > 842812115, > 862975761, > 863130919, > 110753, > 870859136, > 870898732, > 870982260, > 870977388, > 844473760, > 844851728, > 862896011, > 843011267, > 843009055, > 860901832, > 843738160, > 843731504, > 9921, > 9836 ) My code looks like this: ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init]; picker.peoplePickerDelegate = self; [picker setDisplayedProperties:[NSArray arrayWithObject:[NSNumber numberWithInt:kABPersonAddressProperty]]]; [self presentModalViewController:picker animated:YES]; [picker release]; - (void)peoplePickerNavigationControllerDidCancel: (ABPeoplePickerNavigationController *)peoplePicker { [self dismissModalViewControllerAnimated:YES]; } - (BOOL)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person { return YES; } - (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier { // Only inspect the value if it's an address. if (property == kABPersonAddressProperty) { ABMutableMultiValueRef multiValue = ABRecordCopyValue(person, property); for(CFIndex i=0;i<ABMultiValueGetCount(multiValue);i++) { CFDictionaryRef dict = ABMultiValueCopyValueAtIndex(multiValue, i) ; ..... I don't know why it's telling me that an array created this error please help me Edit: Guys, Thanks for the answers, but apparently the problem wasn't even in this code it was a problem from somewhere else really appreciate the help though share|improve this question 2 Answers 2 The log message is telling you exactly what went wrong: *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSCFArray objectAtIndex:]: index (0) beyond bounds (0)' This says the your code is attempting to access the first element (index 0) of an empty array (bounds 0). Before running your for loop, make sure you use ABMultiValueGetCount to see if the array is empty, and only enter the loop if the array's not empty. share|improve this answer Is this on the hardware or the simulator? If you run with debug on the simulator, then the stack trace will show you which of your code lines caused the eventual problem. Although it might be in a library, it will have its origin with one of your code lines. share|improve this answer Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.859828
1 $\begingroup$ Let be $T_{\beta}:[0,1]\to [0,1]$ defined by $T_{\beta}(x)=\beta x \bmod 1$ where $\beta \in (1,2).$ Questions: 1. $T_{\beta}$ is topologically transitive? 2. What about the periodic points? 3. $T_{\beta}$ is topologically mixing ? The answers to this question when beta is equal to 2 comes from the fact that $ T_{\beta}$ is conjugated to two side shift. However in this case $ \beta \in (1,2).$ So my attempt is in brute force, i.e, I ventured to say that the points $x\in \mathbb{R}\setminus \mathbb{Q}$ has dense orbit, since the orbit of $x $ is the set $$\operatorname{Orb}(x)=\{T^n_{\beta}(x), ~~n\in\mathbb{N}\}\;,$$ and $$T^n(x)=\beta^n(x)\bmod 1$$ that is, $$T^n(x)=\beta^nx+l,~~~l\in\mathbb{Z},~~n\in \mathbb{N}.$$ think the above set is dense, for sets of the form $$A=\{nx+m,~~ ~~~l\in\mathbb{Z},~~n\in \mathbb{N}\}$$ when $x$ is irrational. this is not quite a proof ... I'm only showing where my intuition is guiding me. I wonder if anyone can do it more elegantly. $\endgroup$ • $\begingroup$ Enven for the doubling map, not all irrational points have a dense orbit (actually, uncountably many points have a non-dense orbit). $\endgroup$ – D. Thomine Jun 7 '12 at 16:11 0 $\begingroup$ I think you mean $T_\beta\colon [0,1)\to [0,1)$ where $T_\beta(x) = \beta x$ mod $1$, as otherwise the map is not well-defined. Unless I misunderstand, topologically mixing is a stronger condition than topological transitivity: • $T_\beta$ is topologically transitive if for every two nonempty open sets $U$ and $V$ there is some $n$ for which $f^n(U)\cap V \neq \emptyset$. • $T_\beta$ is topologically mixing if for every two nonempty open sets $U$ and $V$ one has $f^n(U)\cap V\neq\emptyset$ for all sufficiently large $n$. For the maps $T_\beta$ something stronger is true: for every nonempty open set $U$, one has $T_\beta^n(U) = [0,1)$ for sufficiently large $n$. Essentially this is because if $U$ is an interval of length $L$, then $\beta^nU$ is an interval of length $\beta^nL$, which for large $n$ will always be $>1$. For periodic points: Suppose $x\in [0,1)$ is $n$-periodic, so $T_\beta^n(x) = x$. This is equivalent to saying that $\beta^nx = x + m$ for some integer $m$, which is in turn equivalent to $$x = \frac{m}{\beta^n-1}$$ for some integer $m$. You therefore get quite a lot of periodic points. $\endgroup$ Your Answer By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
__label__pos
0.998989
What are the different phases of component lifecycle? The component lifecycle has three distinct lifecycle phases: 1. Mounting: The component is ready to mount in the browser DOM. This phase covers initialization from constructor(), getDerivedStateFromProps(), render(), and componentDidMount() lifecycle methods. 2. Updating: In this phase, the component get updated in two ways, sending the new props and updating the state either from setState() or forceUpdate(). This phase covers getDerivedStateFromProps(), shouldComponentUpdate(), render(), getSnapshotBeforeUpdate() and componentDidUpdate() lifecycle methods. 3. Unmounting: In this last phase, the component is not needed and get unmounted from the browser DOM. This phase includes componentWillUnmount() lifecycle method. It's worth mentioning that React internally has a concept of phases when applying changes to the DOM. They are separated as follows 1. Render The component will render without any side-effects. This applies for Pure components and in this phase, React can pause, abort, or restart the render. 2. Pre-commit Before the component actually applies the changes to the DOM, there is a moment that allows React to read from the DOM through the getSnapshotBeforeUpdate(). 3. Commit React works with the DOM and executes the final lifecycles respectively componentDidMount() for mounting, componentDidUpdate() for updating, and componentWillUnmount() for unmounting. React 16.3+ Phases (or an interactive version) phases 16.3+ Before React 16.3 phases 16.2 March 05, 2022 1378
__label__pos
0.993917
Location: PHPKode > projects > WP Post to PDF > wp-post-to-pdf/tcpdf/tcpdf.php <?php //============================================================+ // File name : tcpdf.php // Version : 5.8.034 // Begin : 2002-08-03 // Last Update : 2010-09-27 // Author : Nicola Asuni - Tecnick.com S.r.l - Via Della Pace, 11 - 09044 - Quartucciu (CA) - ITALY - www.tecnick.com - [email protected] // License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html) // ------------------------------------------------------------------- // Copyright (C) 2002-2010 Nicola Asuni - Tecnick.com S.r.l. // // This file is part of TCPDF software library. // // TCPDF is free software: you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // TCPDF 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 Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with TCPDF. If not, see <http://www.gnu.org/licenses/>. // // See LICENSE.TXT file for more information. // ------------------------------------------------------------------- // // Description : This is a PHP class for generating PDF documents without // requiring external extensions. // // NOTE: // This class was originally derived in 2002 from the Public // Domain FPDF class by Olivier Plathey (http://www.fpdf.org), // but now is almost entirely rewritten and contains thousands of // new lines of code and hundreds new features. // // Main features: // * no external libraries are required for the basic functions; // * all standard page formats, custom page formats, custom margins and units of measure; // * UTF-8 Unicode and Right-To-Left languages; // * TrueTypeUnicode, OpenTypeUnicode, TrueType, OpenType, Type1 and CID-0 fonts; // * font subsetting; // * methods to publish some XHTML + CSS code, Javascript and Forms; // * images, graphic (geometric figures) and transformation methods; // * supports JPEG, PNG and SVG images natively, all images supported by GD (GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM) and all images supported via ImagMagick (http://www.imagemagick.org/www/formats.html) // * 1D and 2D barcodes: CODE 39, ANSI MH10.8M-1983, USD-3, 3 of 9, CODE 93, USS-93, Standard 2 of 5, Interleaved 2 of 5, CODE 128 A/B/C, 2 and 5 Digits UPC-Based Extention, EAN 8, EAN 13, UPC-A, UPC-E, MSI, POSTNET, PLANET, RMS4CC (Royal Mail 4-state Customer Code), CBC (Customer Bar Code), KIX (Klant index - Customer index), Intelligent Mail Barcode, Onecode, USPS-B-3200, CODABAR, CODE 11, PHARMACODE, PHARMACODE TWO-TRACKS, QR-Code, PDF417; // * Grayscale, RGB, CMYK, Spot Colors and Transparencies; // * automatic page header and footer management; // * document encryption and digital signature certifications; // * transactions to UNDO commands; // * PDF annotations, including links, text and file attachments; // * text rendering modes (fill, stroke and clipping); // * multiple columns mode; // * bookmarks and table of content; // * text hyphenation; // * automatic page break, line break and text alignments including justification; // * automatic page numbering and page groups; // * move and delete pages; // * page compression (requires php-zlib extension); // * XOBject Templates; // // ----------------------------------------------------------- // THANKS TO: // // Olivier Plathey (http://www.fpdf.org) for original FPDF. // Efthimios Mavrogeorgiadis ([email protected]) for suggestions on RTL language support. // Klemen Vodopivec (http://www.fpdf.de/downloads/addons/37/) for Encryption algorithm. // Warren Sherliker ([email protected]) for better image handling. // dullus for text Justification. // Bob Vincent ([email protected]) for <li> value attribute. // Patrick Benny for text stretch suggestion on Cell(). // Johannes Güntert for JavaScript support. // Denis Van Nuffelen for Dynamic Form. // Jacek Czekaj for multibyte justification // Anthony Ferrara for the reintroduction of legacy image methods. // Sourceforge user 1707880 (hucste) for line-trough mode. // Larry Stanbery for page groups. // Martin Hall-May for transparency. // Aaron C. Spike for Polycurve method. // Mohamad Ali Golkar, Saleh AlMatrafe, Charles Abbott for Arabic and Persian support. // Moritz Wagner and Andreas Wurmser for graphic functions. // Andrew Whitehead for core fonts support. // Esteban Joël Marín for OpenType font conversion. // Teus Hagen for several suggestions and fixes. // Yukihiro Nakadaira for CID-0 CJK fonts fixes. // Kosmas Papachristos for some CSS improvements. // Marcel Partap for some fixes. // Won Kyu Park for several suggestions, fixes and patches. // Dominik Dzienia for QR-code support. // Laurent Minguet for some suggestions. // Christian Deligant for some suggestions and fixes. // Anyone that has reported a bug or sent a suggestion. //============================================================+ /** * This is a PHP class for generating PDF documents without requiring external extensions.<br> * TCPDF project (http://www.tcpdf.org) was originally derived in 2002 from the Public Domain FPDF class by Olivier Plathey (http://www.fpdf.org), but now is almost entirely rewritten.<br> * <h3>TCPDF main features are:</h3> * <ul> * <li>no external libraries are required for the basic functions;</li> * <li>all standard page formats, custom page formats, custom margins and units of measure;</li> * <li>UTF-8 Unicode and Right-To-Left languages;</li> * <li>TrueTypeUnicode, OpenTypeUnicode, TrueType, OpenType, Type1 and CID-0 fonts;</li> * <li>font subsetting;</li> * <li>methods to publish some XHTML + CSS code, Javascript and Forms;</li> * <li>images, graphic (geometric figures) and transformation methods; * <li>supports JPEG, PNG and SVG images natively, all images supported by GD (GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM) and all images supported via ImagMagick (http://www.imagemagick.org/www/formats.html)</li> * <li>1D and 2D barcodes: CODE 39, ANSI MH10.8M-1983, USD-3, 3 of 9, CODE 93, USS-93, Standard 2 of 5, Interleaved 2 of 5, CODE 128 A/B/C, 2 and 5 Digits UPC-Based Extention, EAN 8, EAN 13, UPC-A, UPC-E, MSI, POSTNET, PLANET, RMS4CC (Royal Mail 4-state Customer Code), CBC (Customer Bar Code), KIX (Klant index - Customer index), Intelligent Mail Barcode, Onecode, USPS-B-3200, CODABAR, CODE 11, PHARMACODE, PHARMACODE TWO-TRACKS, QR-Code, PDF417;</li> * <li>Grayscale, RGB, CMYK, Spot Colors and Transparencies;</li> * <li>automatic page header and footer management;</li> * <li>document encryption and digital signature certifications;</li> * <li>transactions to UNDO commands;</li> * <li>PDF annotations, including links, text and file attachments;</li> * <li>text rendering modes (fill, stroke and clipping);</li> * <li>multiple columns mode;</li> * <li>bookmarks and table of content;</li> * <li>text hyphenation;</li> * <li>automatic page break, line break and text alignments including justification;</li> * <li>automatic page numbering and page groups;</li> * <li>move and delete pages;</li> * <li>page compression (requires php-zlib extension);</li> * <li>XOBject Templates;</li> * </ul> * Tools to encode your unicode fonts are on fonts/utils directory.</p> * @package com.tecnick.tcpdf * @abstract Class for generating PDF files on-the-fly without requiring external extensions. * @author Nicola Asuni * @copyright 2002-2010 Nicola Asuni - Tecnick.com S.r.l (www.tecnick.com) Via Della Pace, 11 - 09044 - Quartucciu (CA) - ITALY - www.tecnick.com - [email protected] * @link http://www.tcpdf.org * @license http://www.gnu.org/copyleft/lesser.html LGPL * @version 5.8.034 */ /** * main configuration file */ require_once(dirname(__FILE__).'/config/tcpdf_config.php'); // includes some support files /** * unicode data */ require_once(dirname(__FILE__).'/unicode_data.php'); /** * html colors table */ require_once(dirname(__FILE__).'/htmlcolors.php'); if (!class_exists('TCPDF', false)) { /** * define default PDF document producer */ define('PDF_PRODUCER', 'TCPDF 5.8.034 (http://www.tcpdf.org)'); /** * This is a PHP class for generating PDF documents without requiring external extensions.<br> * TCPDF project (http://www.tcpdf.org) has been originally derived in 2002 from the Public Domain FPDF class by Olivier Plathey (http://www.fpdf.org), but now is almost entirely rewritten.<br> * @name TCPDF * @package com.tecnick.tcpdf * @version 5.8.034 * @author Nicola Asuni - [email protected] * @link http://www.tcpdf.org * @license http://www.gnu.org/copyleft/lesser.html LGPL */ class TCPDF { // protected or Protected properties /** * @var current page number * @access protected */ protected $page; /** * @var current object number * @access protected */ protected $n; /** * @var array of object offsets * @access protected */ protected $offsets; /** * @var buffer holding in-memory PDF * @access protected */ protected $buffer; /** * @var array containing pages * @access protected */ protected $pages = array(); /** * @var current document state * @access protected */ protected $state; /** * @var compression flag * @access protected */ protected $compress; /** * @var current page orientation (P = Portrait, L = Landscape) * @access protected */ protected $CurOrientation; /** * @var Page dimensions * @access protected */ protected $pagedim = array(); /** * @var scale factor (number of points in user unit) * @access protected */ protected $k; /** * @var width of page format in points * @access protected */ protected $fwPt; /** * @var height of page format in points * @access protected */ protected $fhPt; /** * @var current width of page in points * @access protected */ protected $wPt; /** * @var current height of page in points * @access protected */ protected $hPt; /** * @var current width of page in user unit * @access protected */ protected $w; /** * @var current height of page in user unit * @access protected */ protected $h; /** * @var left margin * @access protected */ protected $lMargin; /** * @var top margin * @access protected */ protected $tMargin; /** * @var right margin * @access protected */ protected $rMargin; /** * @var page break margin * @access protected */ protected $bMargin; /** * @var cell internal padding * @access protected */ public $cMargin; /** * @var current horizontal position in user unit for cell positioning * @access protected */ protected $x; /** * @var current vertical position in user unit for cell positioning * @access protected */ protected $y; /** * @var height of last cell printed * @access protected */ protected $lasth; /** * @var line width in user unit * @access protected */ protected $LineWidth; /** * @var array of standard font names * @access protected */ protected $CoreFonts; /** * @var array of used fonts * @access protected */ protected $fonts = array(); /** * @var array of font files * @access protected */ protected $FontFiles = array(); /** * @var array of encoding differences * @access protected */ protected $diffs = array(); /** * @var array of used images * @access protected */ protected $images = array(); /** * @var array of Annotations in pages * @access protected */ protected $PageAnnots = array(); /** * @var array of internal links * @access protected */ protected $links = array(); /** * @var current font family * @access protected */ protected $FontFamily; /** * @var current font style * @access protected */ protected $FontStyle; /** * @var current font ascent (distance between font top and baseline) * @access protected * @since 2.8.000 (2007-03-29) */ protected $FontAscent; /** * @var current font descent (distance between font bottom and baseline) * @access protected * @since 2.8.000 (2007-03-29) */ protected $FontDescent; /** * @var underlining flag * @access protected */ protected $underline; /** * @var overlining flag * @access protected */ protected $overline; /** * @var current font info * @access protected */ protected $CurrentFont; /** * @var current font size in points * @access protected */ protected $FontSizePt; /** * @var current font size in user unit * @access protected */ protected $FontSize; /** * @var commands for drawing color * @access protected */ protected $DrawColor; /** * @var commands for filling color * @access protected */ protected $FillColor; /** * @var commands for text color * @access protected */ protected $TextColor; /** * @var indicates whether fill and text colors are different * @access protected */ protected $ColorFlag; /** * @var automatic page breaking * @access protected */ protected $AutoPageBreak; /** * @var threshold used to trigger page breaks * @access protected */ protected $PageBreakTrigger; /** * @var flag set when processing footer * @access protected */ protected $InFooter = false; /** * @var zoom display mode * @access protected */ protected $ZoomMode; /** * @var layout display mode * @access protected */ protected $LayoutMode; /** * @var title * @access protected */ protected $title = ''; /** * @var subject * @access protected */ protected $subject = ''; /** * @var author * @access protected */ protected $author = ''; /** * @var keywords * @access protected */ protected $keywords = ''; /** * @var creator * @access protected */ protected $creator = ''; /** * @var alias for total number of pages * @access protected */ protected $AliasNbPages = '{nb}'; /** * @var alias for page number * @access protected */ protected $AliasNumPage = '{pnb}'; /** * @var right-bottom corner X coordinate of inserted image * @since 2002-07-31 * @author Nicola Asuni * @access protected */ protected $img_rb_x; /** * @var right-bottom corner Y coordinate of inserted image * @since 2002-07-31 * @author Nicola Asuni * @access protected */ protected $img_rb_y; /** * @var adjusting factor to convert pixels to user units. * @since 2004-06-14 * @author Nicola Asuni * @access protected */ protected $imgscale = 1; /** * @var boolean set to true when the input text is unicode (require unicode fonts) * @since 2005-01-02 * @author Nicola Asuni * @access protected */ protected $isunicode = false; /** * @var PDF version * @since 1.5.3 * @access protected */ protected $PDFVersion = '1.7'; /** * @var Minimum distance between header and top page margin. * @access protected */ protected $header_margin; /** * @var Minimum distance between footer and bottom page margin. * @access protected */ protected $footer_margin; /** * @var original left margin value * @access protected * @since 1.53.0.TC013 */ protected $original_lMargin; /** * @var original right margin value * @access protected * @since 1.53.0.TC013 */ protected $original_rMargin; /** * @var Header font. * @access protected */ protected $header_font; /** * @var Footer font. * @access protected */ protected $footer_font; /** * @var Language templates. * @access protected */ protected $l; /** * @var Barcode to print on page footer (only if set). * @access protected */ protected $barcode = false; /** * @var If true prints header * @access protected */ protected $print_header = true; /** * @var If true prints footer. * @access protected */ protected $print_footer = true; /** * @var Header image logo. * @access protected */ protected $header_logo = ''; /** * @var Header image logo width in mm. * @access protected */ protected $header_logo_width = 30; /** * @var String to print as title on document header. * @access protected */ protected $header_title = ''; /** * @var String to print on document header. * @access protected */ protected $header_string = ''; /** * @var Default number of columns for html table. * @access protected */ protected $default_table_columns = 4; // variables for html parser /** * @var HTML PARSER: array to store current link and rendering styles. * @access protected */ protected $HREF = array(); /** * @var store a list of available fonts on filesystem. * @access protected */ protected $fontlist = array(); /** * @var current foreground color * @access protected */ protected $fgcolor; /** * @var HTML PARSER: array of boolean values, true in case of ordered list (OL), false otherwise. * @access protected */ protected $listordered = array(); /** * @var HTML PARSER: array count list items on nested lists. * @access protected */ protected $listcount = array(); /** * @var HTML PARSER: current list nesting level. * @access protected */ protected $listnum = 0; /** * @var HTML PARSER: indent amount for lists. * @access protected */ protected $listindent = 0; /** * @var HTML PARSER: current list indententation level. * @access protected */ protected $listindentlevel = 0; /** * @var current background color * @access protected */ protected $bgcolor; /** * @var Store temporary font size in points. * @access protected */ protected $tempfontsize = 10; /** * @var spacer for LI tags. * @access protected */ protected $lispacer = ''; /** * @var default encoding * @access protected * @since 1.53.0.TC010 */ protected $encoding = 'UTF-8'; /** * @var PHP internal encoding * @access protected * @since 1.53.0.TC016 */ protected $internal_encoding; /** * @var indicates if the document language is Right-To-Left * @access protected * @since 2.0.000 */ protected $rtl = false; /** * @var used to force RTL or LTR string inversion * @access protected * @since 2.0.000 */ protected $tmprtl = false; // --- Variables used for document encryption: /** * Indicates whether document is protected * @access protected * @since 2.0.000 (2008-01-02) */ protected $encrypted; /** * Array containing encryption settings * @access protected * @since 5.0.005 (2010-05-11) */ protected $encryptdata = array(); /** * last RC4 key encrypted (cached for optimisation) * @access protected * @since 2.0.000 (2008-01-02) */ protected $last_enc_key; /** * last RC4 computed key * @access protected * @since 2.0.000 (2008-01-02) */ protected $last_enc_key_c; /** * Encryption padding * @access protected */ protected $enc_padding = "\x28\xBF\x4E\x5E\x4E\x75\x8A\x41\x64\x00\x4E\x56\xFF\xFA\x01\x08\x2E\x2E\x00\xB6\xD0\x68\x3E\x80\x2F\x0C\xA9\xFE\x64\x53\x69\x7A"; /** * File ID (used on trailer) * @access protected * @since 5.0.005 (2010-05-12) */ protected $file_id; // --- bookmark --- /** * Outlines for bookmark * @access protected * @since 2.1.002 (2008-02-12) */ protected $outlines = array(); /** * Outline root for bookmark * @access protected * @since 2.1.002 (2008-02-12) */ protected $OutlineRoot; // --- javascript and form --- /** * javascript code * @access protected * @since 2.1.002 (2008-02-12) */ protected $javascript = ''; /** * javascript counter * @access protected * @since 2.1.002 (2008-02-12) */ protected $n_js; /** * line trough state * @access protected * @since 2.8.000 (2008-03-19) */ protected $linethrough; /** * Array with additional document-wide usage rights for the document. * @access protected * @since 5.8.014 (2010-08-23) */ protected $ur = array(); /** * Dot Per Inch Document Resolution (do not change) * @access protected * @since 3.0.000 (2008-03-27) */ protected $dpi = 72; /** * Array of page numbers were a new page group was started * @access protected * @since 3.0.000 (2008-03-27) */ protected $newpagegroup = array(); /** * Contains the number of pages of the groups * @access protected * @since 3.0.000 (2008-03-27) */ protected $pagegroups; /** * Contains the alias of the current page group * @access protected * @since 3.0.000 (2008-03-27) */ protected $currpagegroup; /** * Restrict the rendering of some elements to screen or printout. * @access protected * @since 3.0.000 (2008-03-27) */ protected $visibility = 'all'; /** * Print visibility. * @access protected * @since 3.0.000 (2008-03-27) */ protected $n_ocg_print; /** * View visibility. * @access protected * @since 3.0.000 (2008-03-27) */ protected $n_ocg_view; /** * Array of transparency objects and parameters. * @access protected * @since 3.0.000 (2008-03-27) */ protected $extgstates; /** * Set the default JPEG compression quality (1-100) * @access protected * @since 3.0.000 (2008-03-27) */ protected $jpeg_quality; /** * Default cell height ratio. * @access protected * @since 3.0.014 (2008-05-23) */ protected $cell_height_ratio = K_CELL_HEIGHT_RATIO; /** * PDF viewer preferences. * @access protected * @since 3.1.000 (2008-06-09) */ protected $viewer_preferences; /** * A name object specifying how the document should be displayed when opened. * @access protected * @since 3.1.000 (2008-06-09) */ protected $PageMode; /** * Array for storing gradient information. * @access protected * @since 3.1.000 (2008-06-09) */ protected $gradients = array(); /** * Array used to store positions inside the pages buffer. * keys are the page numbers * @access protected * @since 3.2.000 (2008-06-26) */ protected $intmrk = array(); /** * Array used to store positions inside the pages buffer. * keys are the page numbers * @access protected * @since 5.7.000 (2010-08-03) */ protected $bordermrk = array(); /** * Array used to store page positions to track empty pages. * keys are the page numbers * @access protected * @since 5.8.007 (2010-08-18) */ protected $emptypagemrk = array(); /** * Array used to store content positions inside the pages buffer. * keys are the page numbers * @access protected * @since 4.6.021 (2009-07-20) */ protected $cntmrk = array(); /** * Array used to store footer positions of each page. * @access protected * @since 3.2.000 (2008-07-01) */ protected $footerpos = array(); /** * Array used to store footer length of each page. * @access protected * @since 4.0.014 (2008-07-29) */ protected $footerlen = array(); /** * True if a newline is created. * @access protected * @since 3.2.000 (2008-07-01) */ protected $newline = true; /** * End position of the latest inserted line * @access protected * @since 3.2.000 (2008-07-01) */ protected $endlinex = 0; /** * PDF string for last line width * @access protected * @since 4.0.006 (2008-07-16) */ protected $linestyleWidth = ''; /** * PDF string for last line width * @access protected * @since 4.0.006 (2008-07-16) */ protected $linestyleCap = '0 J'; /** * PDF string for last line width * @access protected * @since 4.0.006 (2008-07-16) */ protected $linestyleJoin = '0 j'; /** * PDF string for last line width * @access protected * @since 4.0.006 (2008-07-16) */ protected $linestyleDash = '[] 0 d'; /** * True if marked-content sequence is open * @access protected * @since 4.0.013 (2008-07-28) */ protected $openMarkedContent = false; /** * Count the latest inserted vertical spaces on HTML * @access protected * @since 4.0.021 (2008-08-24) */ protected $htmlvspace = 0; /** * Array of Spot colors * @access protected * @since 4.0.024 (2008-09-12) */ protected $spot_colors = array(); /** * Symbol used for HTML unordered list items * @access protected * @since 4.0.028 (2008-09-26) */ protected $lisymbol = ''; /** * String used to mark the beginning and end of EPS image blocks * @access protected * @since 4.1.000 (2008-10-18) */ protected $epsmarker = 'x#!#EPS#!#x'; /** * Array of transformation matrix * @access protected * @since 4.2.000 (2008-10-29) */ protected $transfmatrix = array(); /** * Current key for transformation matrix * @access protected * @since 4.8.005 (2009-09-17) */ protected $transfmatrix_key = 0; /** * Booklet mode for double-sided pages * @access protected * @since 4.2.000 (2008-10-29) */ protected $booklet = false; /** * Epsilon value used for float calculations * @access protected * @since 4.2.000 (2008-10-29) */ protected $feps = 0.005; /** * Array used for custom vertical spaces for HTML tags * @access protected * @since 4.2.001 (2008-10-30) */ protected $tagvspaces = array(); /** * @var HTML PARSER: custom indent amount for lists. * Negative value means disabled. * @access protected * @since 4.2.007 (2008-11-12) */ protected $customlistindent = -1; /** * @var if true keeps the border open for the cell sides that cross the page. * @access protected * @since 4.2.010 (2008-11-14) */ protected $opencell = true; /** * @var array of files to embedd * @access protected * @since 4.4.000 (2008-12-07) */ protected $embeddedfiles = array(); /** * @var boolean true when inside html pre tag * @access protected * @since 4.4.001 (2008-12-08) */ protected $premode = false; /** * Array used to store positions of graphics transformation blocks inside the page buffer. * keys are the page numbers * @access protected * @since 4.4.002 (2008-12-09) */ protected $transfmrk = array(); /** * Default color for html links * @access protected * @since 4.4.003 (2008-12-09) */ protected $htmlLinkColorArray = array(0, 0, 255); /** * Default font style to add to html links * @access protected * @since 4.4.003 (2008-12-09) */ protected $htmlLinkFontStyle = 'U'; /** * Counts the number of pages. * @access protected * @since 4.5.000 (2008-12-31) */ protected $numpages = 0; /** * Array containing page lengths in bytes. * @access protected * @since 4.5.000 (2008-12-31) */ protected $pagelen = array(); /** * Counts the number of pages. * @access protected * @since 4.5.000 (2008-12-31) */ protected $numimages = 0; /** * Store the image keys. * @access protected * @since 4.5.000 (2008-12-31) */ protected $imagekeys = array(); /** * Length of the buffer in bytes. * @access protected * @since 4.5.000 (2008-12-31) */ protected $bufferlen = 0; /** * If true enables disk caching. * @access protected * @since 4.5.000 (2008-12-31) */ protected $diskcache = false; /** * Counts the number of fonts. * @access protected * @since 4.5.000 (2009-01-02) */ protected $numfonts = 0; /** * Store the font keys. * @access protected * @since 4.5.000 (2009-01-02) */ protected $fontkeys = array(); /** * Store the font object IDs. * @access protected * @since 4.8.001 (2009-09-09) */ protected $font_obj_ids = array(); /** * Store the fage status (true when opened, false when closed). * @access protected * @since 4.5.000 (2009-01-02) */ protected $pageopen = array(); /** * Default monospaced font * @access protected * @since 4.5.025 (2009-03-10) */ protected $default_monospaced_font = 'courier'; /** * Used to store a cloned copy of the current class object * @access protected * @since 4.5.029 (2009-03-19) */ protected $objcopy; /** * Array used to store the lengths of cache files * @access protected * @since 4.5.029 (2009-03-19) */ protected $cache_file_length = array(); /** * Table header content to be repeated on each new page * @access protected * @since 4.5.030 (2009-03-20) */ protected $thead = ''; /** * Margins used for table header. * @access protected * @since 4.5.030 (2009-03-20) */ protected $theadMargins = array(); /** * Cache array for UTF8StringToArray() method. * @access protected * @since 4.5.037 (2009-04-07) */ protected $cache_UTF8StringToArray = array(); /** * Maximum size of cache array used for UTF8StringToArray() method. * @access protected * @since 4.5.037 (2009-04-07) */ protected $cache_maxsize_UTF8StringToArray = 8; /** * Current size of cache array used for UTF8StringToArray() method. * @access protected * @since 4.5.037 (2009-04-07) */ protected $cache_size_UTF8StringToArray = 0; /** * If true enables document signing * @access protected * @since 4.6.005 (2009-04-24) */ protected $sign = false; /** * Signature data * @access protected * @since 4.6.005 (2009-04-24) */ protected $signature_data = array(); /** * Signature max length * @access protected * @since 4.6.005 (2009-04-24) */ protected $signature_max_length = 11742; /** * data for signature appearance * @access protected * @since 5.3.011 (2010-06-16) */ protected $signature_appearance = array('page' => 1, 'rect' => '0 0 0 0'); /** * Regular expression used to find blank characters used for word-wrapping. * @access protected * @since 4.6.006 (2009-04-28) */ protected $re_spaces = '/[^\S\xa0]/'; /** * Array of parts $re_spaces * @access protected * @since 5.5.011 (2010-07-09) */ protected $re_space = array('p' => '[^\S\xa0]', 'm' => ''); /** * Signature object ID * @access protected * @since 4.6.022 (2009-06-23) */ protected $sig_obj_id = 0; /** * ByteRange placemark used during signature process. * @access protected * @since 4.6.028 (2009-08-25) */ protected $byterange_string = '/ByteRange[0 ********** ********** **********]'; /** * Placemark used during signature process. * @access protected * @since 4.6.028 (2009-08-25) */ protected $sig_annot_ref = '***SIGANNREF*** 0 R'; /** * ID of page objects * @access protected * @since 4.7.000 (2009-08-29) */ protected $page_obj_id = array(); /** * List of form annotations IDs * @access protected * @since 4.8.000 (2009-09-07) */ protected $form_obj_id = array(); /** * Deafult Javascript field properties. Possible values are described on official Javascript for Acrobat API reference. Annotation options can be directly specified using the 'aopt' entry. * @access protected * @since 4.8.000 (2009-09-07) */ protected $default_form_prop = array('lineWidth'=>1, 'borderStyle'=>'solid', 'fillColor'=>array(255, 255, 255), 'strokeColor'=>array(128, 128, 128)); /** * Javascript objects array * @access protected * @since 4.8.000 (2009-09-07) */ protected $js_objects = array(); /** * Current form action (used during XHTML rendering) * @access protected * @since 4.8.000 (2009-09-07) */ protected $form_action = ''; /** * Current form encryption type (used during XHTML rendering) * @access protected * @since 4.8.000 (2009-09-07) */ protected $form_enctype = 'application/x-www-form-urlencoded'; /** * Current method to submit forms. * @access protected * @since 4.8.000 (2009-09-07) */ protected $form_mode = 'post'; /** * List of fonts used on form fields (fontname => fontkey). * @access protected * @since 4.8.001 (2009-09-09) */ protected $annotation_fonts = array(); /** * List of radio buttons parent objects. * @access protected * @since 4.8.001 (2009-09-09) */ protected $radiobutton_groups = array(); /** * List of radio group objects IDs * @access protected * @since 4.8.001 (2009-09-09) */ protected $radio_groups = array(); /** * Text indentation value (used for text-indent CSS attribute) * @access protected * @since 4.8.006 (2009-09-23) */ protected $textindent = 0; /** * Store page number when startTransaction() is called. * @access protected * @since 4.8.006 (2009-09-23) */ protected $start_transaction_page = 0; /** * Store Y position when startTransaction() is called. * @access protected * @since 4.9.001 (2010-03-28) */ protected $start_transaction_y = 0; /** * True when we are printing the thead section on a new page * @access protected * @since 4.8.027 (2010-01-25) */ protected $inthead = false; /** * Array of column measures (width, space, starting Y position) * @access protected * @since 4.9.001 (2010-03-28) */ protected $columns = array(); /** * Number of colums * @access protected * @since 4.9.001 (2010-03-28) */ protected $num_columns = 1; /** * Current column number * @access protected * @since 4.9.001 (2010-03-28) */ protected $current_column = 0; /** * Starting page for columns * @access protected * @since 4.9.001 (2010-03-28) */ protected $column_start_page = 0; /** * Maximum page and column selected * @access protected * @since 5.8.000 (2010-08-11) */ protected $maxselcol = array('page' => 0, 'column' => 0); /** * Array of: X difference between table cell x start and starting page margin, cellspacing, cellpadding * @access protected * @since 5.8.000 (2010-08-11) */ protected $colxshift = array('x' => 0, 's' => 0, 'p' => 0); /** * Text rendering mode: 0 = Fill text; 1 = Stroke text; 2 = Fill, then stroke text; 3 = Neither fill nor stroke text (invisible); 4 = Fill text and add to path for clipping; 5 = Stroke text and add to path for clipping; 6 = Fill, then stroke text and add to path for clipping; 7 = Add text to path for clipping. * @access protected * @since 4.9.008 (2010-04-03) */ protected $textrendermode = 0; /** * Text stroke width in doc units * @access protected * @since 4.9.008 (2010-04-03) */ protected $textstrokewidth = 0; /** * @var current stroke color * @access protected * @since 4.9.008 (2010-04-03) */ protected $strokecolor; /** * @var default unit of measure for document * @access protected * @since 5.0.000 (2010-04-22) */ protected $pdfunit = 'mm'; /** * @var true when we are on TOC (Table Of Content) page * @access protected */ protected $tocpage = false; /** * @var If true convert vector images (SVG, EPS) to raster image using GD or ImageMagick library. * @access protected * @since 5.0.000 (2010-04-26) */ protected $rasterize_vector_images = false; /** * @var If true enables font subsetting by default * @access protected * @since 5.3.002 (2010-06-07) */ protected $font_subsetting = true; /** * @var Array of default graphic settings * @access protected * @since 5.5.008 (2010-07-02) */ protected $default_graphic_vars = array(); /** * @var Array of XObjects * @access protected * @since 5.8.014 (2010-08-23) */ protected $xobjects = array(); /** * @var boolean true when we are inside an XObject * @access protected * @since 5.8.017 (2010-08-24) */ protected $inxobj = false; /** * @var current XObject ID * @access protected * @since 5.8.017 (2010-08-24) */ protected $xobjid = ''; /** * @var directory used for the last SVG image * @access protected * @since 5.0.000 (2010-05-05) */ protected $svgdir = ''; /** * @var Deafult unit of measure for SVG * @access protected * @since 5.0.000 (2010-05-02) */ protected $svgunit = 'px'; /** * @var array of SVG gradients * @access protected * @since 5.0.000 (2010-05-02) */ protected $svggradients = array(); /** * @var ID of last SVG gradient * @access protected * @since 5.0.000 (2010-05-02) */ protected $svggradientid = 0; /** * @var true when in SVG defs group * @access protected * @since 5.0.000 (2010-05-02) */ protected $svgdefsmode = false; /** * @var array of SVG defs * @access protected * @since 5.0.000 (2010-05-02) */ protected $svgdefs = array(); /** * @var true when in SVG clipPath tag * @access protected * @since 5.0.000 (2010-04-26) */ protected $svgclipmode = false; /** * @var array of SVG clipPath commands * @access protected * @since 5.0.000 (2010-05-02) */ protected $svgclippaths = array(); /** * @var array of SVG clipPath tranformation matrix * @access protected * @since 5.8.022 (2010-08-31) */ protected $svgcliptm = array(); /** * @var ID of last SVG clipPath * @access protected * @since 5.0.000 (2010-05-02) */ protected $svgclipid = 0; /** * @var svg text * @access protected * @since 5.0.000 (2010-05-02) */ protected $svgtext = ''; /** * @var svg text properties * @access protected * @since 5.8.013 (2010-08-23) */ protected $svgtextmode = array(); /** * @var array of hinheritable SVG properties * @access protected * @since 5.0.000 (2010-05-02) */ protected $svginheritprop = array('clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cursor', 'direction', 'fill', 'fill-opacity', 'fill-rule', 'font', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'image-rendering', 'kerning', 'letter-spacing', 'marker', 'marker-end', 'marker-mid', 'marker-start', 'pointer-events', 'shape-rendering', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-rendering', 'visibility', 'word-spacing', 'writing-mode'); /** * @var array of SVG properties * @access protected * @since 5.0.000 (2010-05-02) */ protected $svgstyles = array(array( 'alignment-baseline' => 'auto', 'baseline-shift' => 'baseline', 'clip' => 'auto', 'clip-path' => 'none', 'clip-rule' => 'nonzero', 'color' => 'black', 'color-interpolation' => 'sRGB', 'color-interpolation-filters' => 'linearRGB', 'color-profile' => 'auto', 'color-rendering' => 'auto', 'cursor' => 'auto', 'direction' => 'ltr', 'display' => 'inline', 'dominant-baseline' => 'auto', 'enable-background' => 'accumulate', 'fill' => 'black', 'fill-opacity' => 1, 'fill-rule' => 'nonzero', 'filter' => 'none', 'flood-color' => 'black', 'flood-opacity' => 1, 'font' => '', 'font-family' => 'helvetica', 'font-size' => 'medium', 'font-size-adjust' => 'none', 'font-stretch' => 'normal', 'font-style' => 'normal', 'font-variant' => 'normal', 'font-weight' => 'normal', 'glyph-orientation-horizontal' => '0deg', 'glyph-orientation-vertical' => 'auto', 'image-rendering' => 'auto', 'kerning' => 'auto', 'letter-spacing' => 'normal', 'lighting-color' => 'white', 'marker' => '', 'marker-end' => 'none', 'marker-mid' => 'none', 'marker-start' => 'none', 'mask' => 'none', 'opacity' => 1, 'overflow' => 'auto', 'pointer-events' => 'visiblePainted', 'shape-rendering' => 'auto', 'stop-color' => 'black', 'stop-opacity' => 1, 'stroke' => 'none', 'stroke-dasharray' => 'none', 'stroke-dashoffset' => 0, 'stroke-linecap' => 'butt', 'stroke-linejoin' => 'miter', 'stroke-miterlimit' => 4, 'stroke-opacity' => 1, 'stroke-width' => 1, 'text-anchor' => 'start', 'text-decoration' => 'none', 'text-rendering' => 'auto', 'unicode-bidi' => 'normal', 'visibility' => 'visible', 'word-spacing' => 'normal', 'writing-mode' => 'lr-tb', 'text-color' => 'black', 'transfmatrix' => array(1, 0, 0, 1, 0, 0) )); //------------------------------------------------------------ // METHODS //------------------------------------------------------------ /** * This is the class constructor. * It allows to set up the page format, the orientation and the measure unit used in all the methods (except for the font sizes). * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or Portrait (default)</li><li>L or Landscape</li><li>'' (empty string) for automatic orientation</li></ul> * @param string $unit User measure unit. Possible values are:<ul><li>pt: point</li><li>mm: millimeter (default)</li><li>cm: centimeter</li><li>in: inch</li></ul><br />A point equals 1/72 of inch, that is to say about 0.35 mm (an inch being 2.54 cm). This is a very common unit in typography; font sizes are expressed in that unit. * @param mixed $format The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() or an array of parameters specified at setPageFormat(). * @param boolean $unicode TRUE means that the input text is unicode (default = true) * @param boolean $diskcache if TRUE reduce the RAM memory usage by caching temporary data on filesystem (slower). * @param String $encoding charset encoding; default is UTF-8 * @access public * @see getPageSizeFromFormat(), setPageFormat() */ public function __construct($orientation='P', $unit='mm', $format='A4', $unicode=true, $encoding='UTF-8', $diskcache=false) { /* Set internal character encoding to ASCII */ if (function_exists('mb_internal_encoding') AND mb_internal_encoding()) { $this->internal_encoding = mb_internal_encoding(); mb_internal_encoding('ASCII'); } $this->font_obj_ids = array(); $this->page_obj_id = array(); $this->form_obj_id = array(); // set disk caching $this->diskcache = $diskcache ? true : false; // set language direction $this->rtl = false; $this->tmprtl = false; //Some checks $this->_dochecks(); //Initialization of properties $this->isunicode = $unicode; $this->page = 0; $this->transfmrk[0] = array(); $this->pagedim = array(); $this->n = 2; $this->buffer = ''; $this->pages = array(); $this->state = 0; $this->fonts = array(); $this->FontFiles = array(); $this->diffs = array(); $this->images = array(); $this->links = array(); $this->gradients = array(); $this->InFooter = false; $this->lasth = 0; $this->FontFamily = 'helvetica'; $this->FontStyle = ''; $this->FontSizePt = 12; $this->underline = false; $this->overline = false; $this->linethrough = false; $this->DrawColor = '0 G'; $this->FillColor = '0 g'; $this->TextColor = '0 g'; $this->ColorFlag = false; // encryption values $this->encrypted = false; $this->last_enc_key = ''; //Standard Unicode fonts $this->CoreFonts = array( 'courier'=>'Courier', 'courierB'=>'Courier-Bold', 'courierI'=>'Courier-Oblique', 'courierBI'=>'Courier-BoldOblique', 'helvetica'=>'Helvetica', 'helveticaB'=>'Helvetica-Bold', 'helveticaI'=>'Helvetica-Oblique', 'helveticaBI'=>'Helvetica-BoldOblique', 'times'=>'Times-Roman', 'timesB'=>'Times-Bold', 'timesI'=>'Times-Italic', 'timesBI'=>'Times-BoldItalic', 'symbol'=>'Symbol', 'zapfdingbats'=>'ZapfDingbats' ); //Set scale factor $this->setPageUnit($unit); // set page format and orientation $this->setPageFormat($format, $orientation); //Page margins (1 cm) $margin = 28.35 / $this->k; $this->SetMargins($margin, $margin); //Interior cell margin $this->cMargin = $margin / 10; //Line width (0.2 mm) $this->LineWidth = 0.57 / $this->k; $this->linestyleWidth = sprintf('%.2F w', ($this->LineWidth * $this->k)); $this->linestyleCap = '0 J'; $this->linestyleJoin = '0 j'; $this->linestyleDash = '[] 0 d'; //Automatic page break $this->SetAutoPageBreak(true, (2 * $margin)); //Full width display mode $this->SetDisplayMode('fullwidth'); //Compression $this->SetCompression(true); //Set default PDF version number $this->PDFVersion = '1.7'; $this->encoding = $encoding; $this->HREF = array(); $this->getFontsList(); $this->fgcolor = array('R' => 0, 'G' => 0, 'B' => 0); $this->strokecolor = array('R' => 0, 'G' => 0, 'B' => 0); $this->bgcolor = array('R' => 255, 'G' => 255, 'B' => 255); $this->extgstates = array(); // user's rights $this->sign = false; $this->ur['enabled'] = false; $this->ur['document'] = '/FullSave'; $this->ur['annots'] = '/Create/Delete/Modify/Copy/Import/Export'; $this->ur['form'] = '/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate'; $this->ur['signature'] = '/Modify'; $this->ur['ef'] = '/Create/Delete/Modify/Import'; $this->ur['formex'] = ''; $this->signature_appearance = array('page' => 1, 'rect' => '0 0 0 0'); // set default JPEG quality $this->jpeg_quality = 75; // initialize some settings $this->utf8Bidi(array(''), ''); // set default font $this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt); // check if PCRE Unicode support is enabled if ($this->isunicode AND (@preg_match('/\pL/u', 'a') == 1)) { // PCRE unicode support is turned ON // \p{Z} or \p{Separator}: any kind of Unicode whitespace or invisible separator. // \p{Lo} or \p{Other_Letter}: a Unicode letter or ideograph that does not have lowercase and uppercase variants. // \p{Lo} is needed because Chinese characters are packed next to each other without spaces in between. //$this->setSpacesRE('/[^\S\P{Z}\P{Lo}\xa0]/u'); $this->setSpacesRE('/[^\S\P{Z}\xa0]/u'); } else { // PCRE unicode support is turned OFF $this->setSpacesRE('/[^\S\xa0]/'); } $this->default_form_prop = array('lineWidth'=>1, 'borderStyle'=>'solid', 'fillColor'=>array(255, 255, 255), 'strokeColor'=>array(128, 128, 128)); // set file ID for trailer $this->file_id = md5(microtime().__FILE__.'TCPDF'.$orientation.$unit.$format.$encoding.uniqid(''.rand())); // get default graphic vars $this->default_graphic_vars = $this->getGraphicVars(); } /** * Default destructor. * @access public * @since 1.53.0.TC016 */ public function __destruct() { // restore internal encoding if (isset($this->internal_encoding) AND !empty($this->internal_encoding)) { mb_internal_encoding($this->internal_encoding); } // unset all class variables $this->_destroy(true); } /** * Set the units of measure for the document. * @param string $unit User measure unit. Possible values are:<ul><li>pt: point</li><li>mm: millimeter (default)</li><li>cm: centimeter</li><li>in: inch</li></ul><br />A point equals 1/72 of inch, that is to say about 0.35 mm (an inch being 2.54 cm). This is a very common unit in typography; font sizes are expressed in that unit. * @access public * @since 3.0.015 (2008-06-06) */ public function setPageUnit($unit) { $unit = strtolower($unit); //Set scale factor switch ($unit) { // points case 'px': case 'pt': { $this->k = 1; break; } // millimeters case 'mm': { $this->k = $this->dpi / 25.4; break; } // centimeters case 'cm': { $this->k = $this->dpi / 2.54; break; } // inches case 'in': { $this->k = $this->dpi; break; } // unsupported unit default : { $this->Error('Incorrect unit: '.$unit); break; } } $this->pdfunit = $unit; if (isset($this->CurOrientation)) { $this->setPageOrientation($this->CurOrientation); } } /** * Get page dimensions from format name. * @param mixed $format The format name. It can be: <ul> * <li><b>ISO 216 A Series + 2 SIS 014711 extensions</b></li> * <li>A0 (841x1189 mm ; 33.11x46.81 in)</li> * <li>A1 (594x841 mm ; 23.39x33.11 in)</li> * <li>A2 (420x594 mm ; 16.54x23.39 in)</li> * <li>A3 (297x420 mm ; 11.69x16.54 in)</li> * <li>A4 (210x297 mm ; 8.27x11.69 in)</li> * <li>A5 (148x210 mm ; 5.83x8.27 in)</li> * <li>A6 (105x148 mm ; 4.13x5.83 in)</li> * <li>A7 (74x105 mm ; 2.91x4.13 in)</li> * <li>A8 (52x74 mm ; 2.05x2.91 in)</li> * <li>A9 (37x52 mm ; 1.46x2.05 in)</li> * <li>A10 (26x37 mm ; 1.02x1.46 in)</li> * <li>A11 (18x26 mm ; 0.71x1.02 in)</li> * <li>A12 (13x18 mm ; 0.51x0.71 in)</li> * <li><b>ISO 216 B Series + 2 SIS 014711 extensions</b></li> * <li>B0 (1000x1414 mm ; 39.37x55.67 in)</li> * <li>B1 (707x1000 mm ; 27.83x39.37 in)</li> * <li>B2 (500x707 mm ; 19.69x27.83 in)</li> * <li>B3 (353x500 mm ; 13.90x19.69 in)</li> * <li>B4 (250x353 mm ; 9.84x13.90 in)</li> * <li>B5 (176x250 mm ; 6.93x9.84 in)</li> * <li>B6 (125x176 mm ; 4.92x6.93 in)</li> * <li>B7 (88x125 mm ; 3.46x4.92 in)</li> * <li>B8 (62x88 mm ; 2.44x3.46 in)</li> * <li>B9 (44x62 mm ; 1.73x2.44 in)</li> * <li>B10 (31x44 mm ; 1.22x1.73 in)</li> * <li>B11 (22x31 mm ; 0.87x1.22 in)</li> * <li>B12 (15x22 mm ; 0.59x0.87 in)</li> * <li><b>ISO 216 C Series + 2 SIS 014711 extensions + 2 EXTENSION</b></li> * <li>C0 (917x1297 mm ; 36.10x51.06 in)</li> * <li>C1 (648x917 mm ; 25.51x36.10 in)</li> * <li>C2 (458x648 mm ; 18.03x25.51 in)</li> * <li>C3 (324x458 mm ; 12.76x18.03 in)</li> * <li>C4 (229x324 mm ; 9.02x12.76 in)</li> * <li>C5 (162x229 mm ; 6.38x9.02 in)</li> * <li>C6 (114x162 mm ; 4.49x6.38 in)</li> * <li>C7 (81x114 mm ; 3.19x4.49 in)</li> * <li>C8 (57x81 mm ; 2.24x3.19 in)</li> * <li>C9 (40x57 mm ; 1.57x2.24 in)</li> * <li>C10 (28x40 mm ; 1.10x1.57 in)</li> * <li>C11 (20x28 mm ; 0.79x1.10 in)</li> * <li>C12 (14x20 mm ; 0.55x0.79 in)</li> * <li>C76 (81x162 mm ; 3.19x6.38 in)</li> * <li>DL (110x220 mm ; 4.33x8.66 in)</li> * <li><b>SIS 014711 E Series</b></li> * <li>E0 (879x1241 mm ; 34.61x48.86 in)</li> * <li>E1 (620x879 mm ; 24.41x34.61 in)</li> * <li>E2 (440x620 mm ; 17.32x24.41 in)</li> * <li>E3 (310x440 mm ; 12.20x17.32 in)</li> * <li>E4 (220x310 mm ; 8.66x12.20 in)</li> * <li>E5 (155x220 mm ; 6.10x8.66 in)</li> * <li>E6 (110x155 mm ; 4.33x6.10 in)</li> * <li>E7 (78x110 mm ; 3.07x4.33 in)</li> * <li>E8 (55x78 mm ; 2.17x3.07 in)</li> * <li>E9 (39x55 mm ; 1.54x2.17 in)</li> * <li>E10 (27x39 mm ; 1.06x1.54 in)</li> * <li>E11 (19x27 mm ; 0.75x1.06 in)</li> * <li>E12 (13x19 mm ; 0.51x0.75 in)</li> * <li><b>SIS 014711 G Series</b></li> * <li>G0 (958x1354 mm ; 37.72x53.31 in)</li> * <li>G1 (677x958 mm ; 26.65x37.72 in)</li> * <li>G2 (479x677 mm ; 18.86x26.65 in)</li> * <li>G3 (338x479 mm ; 13.31x18.86 in)</li> * <li>G4 (239x338 mm ; 9.41x13.31 in)</li> * <li>G5 (169x239 mm ; 6.65x9.41 in)</li> * <li>G6 (119x169 mm ; 4.69x6.65 in)</li> * <li>G7 (84x119 mm ; 3.31x4.69 in)</li> * <li>G8 (59x84 mm ; 2.32x3.31 in)</li> * <li>G9 (42x59 mm ; 1.65x2.32 in)</li> * <li>G10 (29x42 mm ; 1.14x1.65 in)</li> * <li>G11 (21x29 mm ; 0.83x1.14 in)</li> * <li>G12 (14x21 mm ; 0.55x0.83 in)</li> * <li><b>ISO Press</b></li> * <li>RA0 (860x1220 mm ; 33.86x48.03 in)</li> * <li>RA1 (610x860 mm ; 24.02x33.86 in)</li> * <li>RA2 (430x610 mm ; 16.93x24.02 in)</li> * <li>RA3 (305x430 mm ; 12.01x16.93 in)</li> * <li>RA4 (215x305 mm ; 8.46x12.01 in)</li> * <li>SRA0 (900x1280 mm ; 35.43x50.39 in)</li> * <li>SRA1 (640x900 mm ; 25.20x35.43 in)</li> * <li>SRA2 (450x640 mm ; 17.72x25.20 in)</li> * <li>SRA3 (320x450 mm ; 12.60x17.72 in)</li> * <li>SRA4 (225x320 mm ; 8.86x12.60 in)</li> * <li><b>German DIN 476</b></li> * <li>4A0 (1682x2378 mm ; 66.22x93.62 in)</li> * <li>2A0 (1189x1682 mm ; 46.81x66.22 in)</li> * <li><b>Variations on the ISO Standard</b></li> * <li>A2_EXTRA (445x619 mm ; 17.52x24.37 in)</li> * <li>A3+ (329x483 mm ; 12.95x19.02 in)</li> * <li>A3_EXTRA (322x445 mm ; 12.68x17.52 in)</li> * <li>A3_SUPER (305x508 mm ; 12.01x20.00 in)</li> * <li>SUPER_A3 (305x487 mm ; 12.01x19.17 in)</li> * <li>A4_EXTRA (235x322 mm ; 9.25x12.68 in)</li> * <li>A4_SUPER (229x322 mm ; 9.02x12.68 in)</li> * <li>SUPER_A4 (227x356 mm ; 8.94x14.02 in)</li> * <li>A4_LONG (210x348 mm ; 8.27x13.70 in)</li> * <li>F4 (210x330 mm ; 8.27x12.99 in)</li> * <li>SO_B5_EXTRA (202x276 mm ; 7.95x10.87 in)</li> * <li>A5_EXTRA (173x235 mm ; 6.81x9.25 in)</li> * <li><b>ANSI Series</b></li> * <li>ANSI_E (864x1118 mm ; 34.00x44.00 in)</li> * <li>ANSI_D (559x864 mm ; 22.00x34.00 in)</li> * <li>ANSI_C (432x559 mm ; 17.00x22.00 in)</li> * <li>ANSI_B (279x432 mm ; 11.00x17.00 in)</li> * <li>ANSI_A (216x279 mm ; 8.50x11.00 in)</li> * <li><b>Traditional 'Loose' North American Paper Sizes</b></li> * <li>LEDGER, USLEDGER (432x279 mm ; 17.00x11.00 in)</li> * <li>TABLOID, USTABLOID, BIBLE, ORGANIZERK (279x432 mm ; 11.00x17.00 in)</li> * <li>LETTER, USLETTER, ORGANIZERM (216x279 mm ; 8.50x11.00 in)</li> * <li>LEGAL, USLEGAL (216x356 mm ; 8.50x14.00 in)</li> * <li>GLETTER, GOVERNMENTLETTER (203x267 mm ; 8.00x10.50 in)</li> * <li>JLEGAL, JUNIORLEGAL (203x127 mm ; 8.00x5.00 in)</li> * <li><b>Other North American Paper Sizes</b></li> * <li>QUADDEMY (889x1143 mm ; 35.00x45.00 in)</li> * <li>SUPER_B (330x483 mm ; 13.00x19.00 in)</li> * <li>QUARTO (229x279 mm ; 9.00x11.00 in)</li> * <li>FOLIO, GOVERNMENTLEGAL (216x330 mm ; 8.50x13.00 in)</li> * <li>EXECUTIVE, MONARCH (184x267 mm ; 7.25x10.50 in)</li> * <li>MEMO, STATEMENT, ORGANIZERL (140x216 mm ; 5.50x8.50 in)</li> * <li>FOOLSCAP (210x330 mm ; 8.27x13.00 in)</li> * <li>COMPACT (108x171 mm ; 4.25x6.75 in)</li> * <li>ORGANIZERJ (70x127 mm ; 2.75x5.00 in)</li> * <li><b>Canadian standard CAN 2-9.60M</b></li> * <li>P1 (560x860 mm ; 22.05x33.86 in)</li> * <li>P2 (430x560 mm ; 16.93x22.05 in)</li> * <li>P3 (280x430 mm ; 11.02x16.93 in)</li> * <li>P4 (215x280 mm ; 8.46x11.02 in)</li> * <li>P5 (140x215 mm ; 5.51x8.46 in)</li> * <li>P6 (107x140 mm ; 4.21x5.51 in)</li> * <li><b>North American Architectural Sizes</b></li> * <li>ARCH_E (914x1219 mm ; 36.00x48.00 in)</li> * <li>ARCH_E1 (762x1067 mm ; 30.00x42.00 in)</li> * <li>ARCH_D (610x914 mm ; 24.00x36.00 in)</li> * <li>ARCH_C, BROADSHEET (457x610 mm ; 18.00x24.00 in)</li> * <li>ARCH_B (305x457 mm ; 12.00x18.00 in)</li> * <li>ARCH_A (229x305 mm ; 9.00x12.00 in)</li> * <li><b>Announcement Envelopes</b></li> * <li>ANNENV_A2 (111x146 mm ; 4.37x5.75 in)</li> * <li>ANNENV_A6 (121x165 mm ; 4.75x6.50 in)</li> * <li>ANNENV_A7 (133x184 mm ; 5.25x7.25 in)</li> * <li>ANNENV_A8 (140x206 mm ; 5.50x8.12 in)</li> * <li>ANNENV_A10 (159x244 mm ; 6.25x9.62 in)</li> * <li>ANNENV_SLIM (98x225 mm ; 3.87x8.87 in)</li> * <li><b>Commercial Envelopes</b></li> * <li>COMMENV_N6_1/4 (89x152 mm ; 3.50x6.00 in)</li> * <li>COMMENV_N6_3/4 (92x165 mm ; 3.62x6.50 in)</li> * <li>COMMENV_N8 (98x191 mm ; 3.87x7.50 in)</li> * <li>COMMENV_N9 (98x225 mm ; 3.87x8.87 in)</li> * <li>COMMENV_N10 (105x241 mm ; 4.12x9.50 in)</li> * <li>COMMENV_N11 (114x263 mm ; 4.50x10.37 in)</li> * <li>COMMENV_N12 (121x279 mm ; 4.75x11.00 in)</li> * <li>COMMENV_N14 (127x292 mm ; 5.00x11.50 in)</li> * <li><b>Catalogue Envelopes</b></li> * <li>CATENV_N1 (152x229 mm ; 6.00x9.00 in)</li> * <li>CATENV_N1_3/4 (165x241 mm ; 6.50x9.50 in)</li> * <li>CATENV_N2 (165x254 mm ; 6.50x10.00 in)</li> * <li>CATENV_N3 (178x254 mm ; 7.00x10.00 in)</li> * <li>CATENV_N6 (191x267 mm ; 7.50x10.50 in)</li> * <li>CATENV_N7 (203x279 mm ; 8.00x11.00 in)</li> * <li>CATENV_N8 (210x286 mm ; 8.25x11.25 in)</li> * <li>CATENV_N9_1/2 (216x267 mm ; 8.50x10.50 in)</li> * <li>CATENV_N9_3/4 (222x286 mm ; 8.75x11.25 in)</li> * <li>CATENV_N10_1/2 (229x305 mm ; 9.00x12.00 in)</li> * <li>CATENV_N12_1/2 (241x318 mm ; 9.50x12.50 in)</li> * <li>CATENV_N13_1/2 (254x330 mm ; 10.00x13.00 in)</li> * <li>CATENV_N14_1/4 (286x311 mm ; 11.25x12.25 in)</li> * <li>CATENV_N14_1/2 (292x368 mm ; 11.50x14.50 in)</li> * <li><b>Japanese (JIS P 0138-61) Standard B-Series</b></li> * <li>JIS_B0 (1030x1456 mm ; 40.55x57.32 in)</li> * <li>JIS_B1 (728x1030 mm ; 28.66x40.55 in)</li> * <li>JIS_B2 (515x728 mm ; 20.28x28.66 in)</li> * <li>JIS_B3 (364x515 mm ; 14.33x20.28 in)</li> * <li>JIS_B4 (257x364 mm ; 10.12x14.33 in)</li> * <li>JIS_B5 (182x257 mm ; 7.17x10.12 in)</li> * <li>JIS_B6 (128x182 mm ; 5.04x7.17 in)</li> * <li>JIS_B7 (91x128 mm ; 3.58x5.04 in)</li> * <li>JIS_B8 (64x91 mm ; 2.52x3.58 in)</li> * <li>JIS_B9 (45x64 mm ; 1.77x2.52 in)</li> * <li>JIS_B10 (32x45 mm ; 1.26x1.77 in)</li> * <li>JIS_B11 (22x32 mm ; 0.87x1.26 in)</li> * <li>JIS_B12 (16x22 mm ; 0.63x0.87 in)</li> * <li><b>PA Series</b></li> * <li>PA0 (840x1120 mm ; 33.07x44.09 in)</li> * <li>PA1 (560x840 mm ; 22.05x33.07 in)</li> * <li>PA2 (420x560 mm ; 16.54x22.05 in)</li> * <li>PA3 (280x420 mm ; 11.02x16.54 in)</li> * <li>PA4 (210x280 mm ; 8.27x11.02 in)</li> * <li>PA5 (140x210 mm ; 5.51x8.27 in)</li> * <li>PA6 (105x140 mm ; 4.13x5.51 in)</li> * <li>PA7 (70x105 mm ; 2.76x4.13 in)</li> * <li>PA8 (52x70 mm ; 2.05x2.76 in)</li> * <li>PA9 (35x52 mm ; 1.38x2.05 in)</li> * <li>PA10 (26x35 mm ; 1.02x1.38 in)</li> * <li><b>Standard Photographic Print Sizes</b></li> * <li>PASSPORT_PHOTO (35x45 mm ; 1.38x1.77 in)</li> * <li>E (82x120 mm ; 3.25x4.72 in)</li> * <li>3R, L (89x127 mm ; 3.50x5.00 in)</li> * <li>4R, KG (102x152 mm ; 4.02x5.98 in)</li> * <li>4D (120x152 mm ; 4.72x5.98 in)</li> * <li>5R, 2L (127x178 mm ; 5.00x7.01 in)</li> * <li>6R, 8P (152x203 mm ; 5.98x7.99 in)</li> * <li>8R, 6P (203x254 mm ; 7.99x10.00 in)</li> * <li>S8R, 6PW (203x305 mm ; 7.99x12.01 in)</li> * <li>10R, 4P (254x305 mm ; 10.00x12.01 in)</li> * <li>S10R, 4PW (254x381 mm ; 10.00x15.00 in)</li> * <li>11R (279x356 mm ; 10.98x14.02 in)</li> * <li>S11R (279x432 mm ; 10.98x17.01 in)</li> * <li>12R (305x381 mm ; 12.01x15.00 in)</li> * <li>S12R (305x456 mm ; 12.01x17.95 in)</li> * <li><b>Common Newspaper Sizes</b></li> * <li>NEWSPAPER_BROADSHEET (750x600 mm ; 29.53x23.62 in)</li> * <li>NEWSPAPER_BERLINER (470x315 mm ; 18.50x12.40 in)</li> * <li>NEWSPAPER_COMPACT, NEWSPAPER_TABLOID (430x280 mm ; 16.93x11.02 in)</li> * <li><b>Business Cards</b></li> * <li>CREDIT_CARD, BUSINESS_CARD, BUSINESS_CARD_ISO7810 (54x86 mm ; 2.13x3.37 in)</li> * <li>BUSINESS_CARD_ISO216 (52x74 mm ; 2.05x2.91 in)</li> * <li>BUSINESS_CARD_IT, BUSINESS_CARD_UK, BUSINESS_CARD_FR, BUSINESS_CARD_DE, BUSINESS_CARD_ES (55x85 mm ; 2.17x3.35 in)</li> * <li>BUSINESS_CARD_US, BUSINESS_CARD_CA (51x89 mm ; 2.01x3.50 in)</li> * <li>BUSINESS_CARD_JP (55x91 mm ; 2.17x3.58 in)</li> * <li>BUSINESS_CARD_HK (54x90 mm ; 2.13x3.54 in)</li> * <li>BUSINESS_CARD_AU, BUSINESS_CARD_DK, BUSINESS_CARD_SE (55x90 mm ; 2.17x3.54 in)</li> * <li>BUSINESS_CARD_RU, BUSINESS_CARD_CZ, BUSINESS_CARD_FI, BUSINESS_CARD_HU, BUSINESS_CARD_IL (50x90 mm ; 1.97x3.54 in)</li> * <li><b>Billboards</b></li> * <li>4SHEET (1016x1524 mm ; 40.00x60.00 in)</li> * <li>6SHEET (1200x1800 mm ; 47.24x70.87 in)</li> * <li>12SHEET (3048x1524 mm ; 120.00x60.00 in)</li> * <li>16SHEET (2032x3048 mm ; 80.00x120.00 in)</li> * <li>32SHEET (4064x3048 mm ; 160.00x120.00 in)</li> * <li>48SHEET (6096x3048 mm ; 240.00x120.00 in)</li> * <li>64SHEET (8128x3048 mm ; 320.00x120.00 in)</li> * <li>96SHEET (12192x3048 mm ; 480.00x120.00 in)</li> * <li><b>Old Imperial English (some are still used in USA)</b></li> * <li>EN_EMPEROR (1219x1829 mm ; 48.00x72.00 in)</li> * <li>EN_ANTIQUARIAN (787x1346 mm ; 31.00x53.00 in)</li> * <li>EN_GRAND_EAGLE (730x1067 mm ; 28.75x42.00 in)</li> * <li>EN_DOUBLE_ELEPHANT (679x1016 mm ; 26.75x40.00 in)</li> * <li>EN_ATLAS (660x864 mm ; 26.00x34.00 in)</li> * <li>EN_COLOMBIER (597x876 mm ; 23.50x34.50 in)</li> * <li>EN_ELEPHANT (584x711 mm ; 23.00x28.00 in)</li> * <li>EN_DOUBLE_DEMY (572x902 mm ; 22.50x35.50 in)</li> * <li>EN_IMPERIAL (559x762 mm ; 22.00x30.00 in)</li> * <li>EN_PRINCESS (546x711 mm ; 21.50x28.00 in)</li> * <li>EN_CARTRIDGE (533x660 mm ; 21.00x26.00 in)</li> * <li>EN_DOUBLE_LARGE_POST (533x838 mm ; 21.00x33.00 in)</li> * <li>EN_ROYAL (508x635 mm ; 20.00x25.00 in)</li> * <li>EN_SHEET, EN_HALF_POST (495x597 mm ; 19.50x23.50 in)</li> * <li>EN_SUPER_ROYAL (483x686 mm ; 19.00x27.00 in)</li> * <li>EN_DOUBLE_POST (483x775 mm ; 19.00x30.50 in)</li> * <li>EN_MEDIUM (445x584 mm ; 17.50x23.00 in)</li> * <li>EN_DEMY (445x572 mm ; 17.50x22.50 in)</li> * <li>EN_LARGE_POST (419x533 mm ; 16.50x21.00 in)</li> * <li>EN_COPY_DRAUGHT (406x508 mm ; 16.00x20.00 in)</li> * <li>EN_POST (394x489 mm ; 15.50x19.25 in)</li> * <li>EN_CROWN (381x508 mm ; 15.00x20.00 in)</li> * <li>EN_PINCHED_POST (375x470 mm ; 14.75x18.50 in)</li> * <li>EN_BRIEF (343x406 mm ; 13.50x16.00 in)</li> * <li>EN_FOOLSCAP (343x432 mm ; 13.50x17.00 in)</li> * <li>EN_SMALL_FOOLSCAP (337x419 mm ; 13.25x16.50 in)</li> * <li>EN_POTT (318x381 mm ; 12.50x15.00 in)</li> * <li><b>Old Imperial Belgian</b></li> * <li>BE_GRAND_AIGLE (700x1040 mm ; 27.56x40.94 in)</li> * <li>BE_COLOMBIER (620x850 mm ; 24.41x33.46 in)</li> * <li>BE_DOUBLE_CARRE (620x920 mm ; 24.41x36.22 in)</li> * <li>BE_ELEPHANT (616x770 mm ; 24.25x30.31 in)</li> * <li>BE_PETIT_AIGLE (600x840 mm ; 23.62x33.07 in)</li> * <li>BE_GRAND_JESUS (550x730 mm ; 21.65x28.74 in)</li> * <li>BE_JESUS (540x730 mm ; 21.26x28.74 in)</li> * <li>BE_RAISIN (500x650 mm ; 19.69x25.59 in)</li> * <li>BE_GRAND_MEDIAN (460x605 mm ; 18.11x23.82 in)</li> * <li>BE_DOUBLE_POSTE (435x565 mm ; 17.13x22.24 in)</li> * <li>BE_COQUILLE (430x560 mm ; 16.93x22.05 in)</li> * <li>BE_PETIT_MEDIAN (415x530 mm ; 16.34x20.87 in)</li> * <li>BE_RUCHE (360x460 mm ; 14.17x18.11 in)</li> * <li>BE_PROPATRIA (345x430 mm ; 13.58x16.93 in)</li> * <li>BE_LYS (317x397 mm ; 12.48x15.63 in)</li> * <li>BE_POT (307x384 mm ; 12.09x15.12 in)</li> * <li>BE_ROSETTE (270x347 mm ; 10.63x13.66 in)</li> * <li><b>Old Imperial French</b></li> * <li>FR_UNIVERS (1000x1300 mm ; 39.37x51.18 in)</li> * <li>FR_DOUBLE_COLOMBIER (900x1260 mm ; 35.43x49.61 in)</li> * <li>FR_GRANDE_MONDE (900x1260 mm ; 35.43x49.61 in)</li> * <li>FR_DOUBLE_SOLEIL (800x1200 mm ; 31.50x47.24 in)</li> * <li>FR_DOUBLE_JESUS (760x1120 mm ; 29.92x44.09 in)</li> * <li>FR_GRAND_AIGLE (750x1060 mm ; 29.53x41.73 in)</li> * <li>FR_PETIT_AIGLE (700x940 mm ; 27.56x37.01 in)</li> * <li>FR_DOUBLE_RAISIN (650x1000 mm ; 25.59x39.37 in)</li> * <li>FR_JOURNAL (650x940 mm ; 25.59x37.01 in)</li> * <li>FR_COLOMBIER_AFFICHE (630x900 mm ; 24.80x35.43 in)</li> * <li>FR_DOUBLE_CAVALIER (620x920 mm ; 24.41x36.22 in)</li> * <li>FR_CLOCHE (600x800 mm ; 23.62x31.50 in)</li> * <li>FR_SOLEIL (600x800 mm ; 23.62x31.50 in)</li> * <li>FR_DOUBLE_CARRE (560x900 mm ; 22.05x35.43 in)</li> * <li>FR_DOUBLE_COQUILLE (560x880 mm ; 22.05x34.65 in)</li> * <li>FR_JESUS (560x760 mm ; 22.05x29.92 in)</li> * <li>FR_RAISIN (500x650 mm ; 19.69x25.59 in)</li> * <li>FR_CAVALIER (460x620 mm ; 18.11x24.41 in)</li> * <li>FR_DOUBLE_COURONNE (460x720 mm ; 18.11x28.35 in)</li> * <li>FR_CARRE (450x560 mm ; 17.72x22.05 in)</li> * <li>FR_COQUILLE (440x560 mm ; 17.32x22.05 in)</li> * <li>FR_DOUBLE_TELLIERE (440x680 mm ; 17.32x26.77 in)</li> * <li>FR_DOUBLE_CLOCHE (400x600 mm ; 15.75x23.62 in)</li> * <li>FR_DOUBLE_POT (400x620 mm ; 15.75x24.41 in)</li> * <li>FR_ECU (400x520 mm ; 15.75x20.47 in)</li> * <li>FR_COURONNE (360x460 mm ; 14.17x18.11 in)</li> * <li>FR_TELLIERE (340x440 mm ; 13.39x17.32 in)</li> * <li>FR_POT (310x400 mm ; 12.20x15.75 in)</li> * </ul> * @return array containing page width and height in points * @access public * @since 5.0.010 (2010-05-17) */ public function getPageSizeFromFormat($format) { // Paper cordinates are calculated in this way: (inches * 72) where (1 inch = 25.4 mm) switch (strtoupper($format)) { // ISO 216 A Series + 2 SIS 014711 extensions case 'A0' : {$pf = array( 2383.937, 3370.394); break;} case 'A1' : {$pf = array( 1683.780, 2383.937); break;} case 'A2' : {$pf = array( 1190.551, 1683.780); break;} case 'A3' : {$pf = array( 841.890, 1190.551); break;} case 'A4' : {$pf = array( 595.276, 841.890); break;} case 'A5' : {$pf = array( 419.528, 595.276); break;} case 'A6' : {$pf = array( 297.638, 419.528); break;} case 'A7' : {$pf = array( 209.764, 297.638); break;} case 'A8' : {$pf = array( 147.402, 209.764); break;} case 'A9' : {$pf = array( 104.882, 147.402); break;} case 'A10': {$pf = array( 73.701, 104.882); break;} case 'A11': {$pf = array( 51.024, 73.701); break;} case 'A12': {$pf = array( 36.850, 51.024); break;} // ISO 216 B Series + 2 SIS 014711 extensions case 'B0' : {$pf = array( 2834.646, 4008.189); break;} case 'B1' : {$pf = array( 2004.094, 2834.646); break;} case 'B2' : {$pf = array( 1417.323, 2004.094); break;} case 'B3' : {$pf = array( 1000.630, 1417.323); break;} case 'B4' : {$pf = array( 708.661, 1000.630); break;} case 'B5' : {$pf = array( 498.898, 708.661); break;} case 'B6' : {$pf = array( 354.331, 498.898); break;} case 'B7' : {$pf = array( 249.449, 354.331); break;} case 'B8' : {$pf = array( 175.748, 249.449); break;} case 'B9' : {$pf = array( 124.724, 175.748); break;} case 'B10': {$pf = array( 87.874, 124.724); break;} case 'B11': {$pf = array( 62.362, 87.874); break;} case 'B12': {$pf = array( 42.520, 62.362); break;} // ISO 216 C Series + 2 SIS 014711 extensions + 2 EXTENSION case 'C0' : {$pf = array( 2599.370, 3676.535); break;} case 'C1' : {$pf = array( 1836.850, 2599.370); break;} case 'C2' : {$pf = array( 1298.268, 1836.850); break;} case 'C3' : {$pf = array( 918.425, 1298.268); break;} case 'C4' : {$pf = array( 649.134, 918.425); break;} case 'C5' : {$pf = array( 459.213, 649.134); break;} case 'C6' : {$pf = array( 323.150, 459.213); break;} case 'C7' : {$pf = array( 229.606, 323.150); break;} case 'C8' : {$pf = array( 161.575, 229.606); break;} case 'C9' : {$pf = array( 113.386, 161.575); break;} case 'C10': {$pf = array( 79.370, 113.386); break;} case 'C11': {$pf = array( 56.693, 79.370); break;} case 'C12': {$pf = array( 39.685, 56.693); break;} case 'C76': {$pf = array( 229.606, 459.213); break;} case 'DL' : {$pf = array( 311.811, 623.622); break;} // SIS 014711 E Series case 'E0' : {$pf = array( 2491.654, 3517.795); break;} case 'E1' : {$pf = array( 1757.480, 2491.654); break;} case 'E2' : {$pf = array( 1247.244, 1757.480); break;} case 'E3' : {$pf = array( 878.740, 1247.244); break;} case 'E4' : {$pf = array( 623.622, 878.740); break;} case 'E5' : {$pf = array( 439.370, 623.622); break;} case 'E6' : {$pf = array( 311.811, 439.370); break;} case 'E7' : {$pf = array( 221.102, 311.811); break;} case 'E8' : {$pf = array( 155.906, 221.102); break;} case 'E9' : {$pf = array( 110.551, 155.906); break;} case 'E10': {$pf = array( 76.535, 110.551); break;} case 'E11': {$pf = array( 53.858, 76.535); break;} case 'E12': {$pf = array( 36.850, 53.858); break;} // SIS 014711 G Series case 'G0' : {$pf = array( 2715.591, 3838.110); break;} case 'G1' : {$pf = array( 1919.055, 2715.591); break;} case 'G2' : {$pf = array( 1357.795, 1919.055); break;} case 'G3' : {$pf = array( 958.110, 1357.795); break;} case 'G4' : {$pf = array( 677.480, 958.110); break;} case 'G5' : {$pf = array( 479.055, 677.480); break;} case 'G6' : {$pf = array( 337.323, 479.055); break;} case 'G7' : {$pf = array( 238.110, 337.323); break;} case 'G8' : {$pf = array( 167.244, 238.110); break;} case 'G9' : {$pf = array( 119.055, 167.244); break;} case 'G10': {$pf = array( 82.205, 119.055); break;} case 'G11': {$pf = array( 59.528, 82.205); break;} case 'G12': {$pf = array( 39.685, 59.528); break;} // ISO Press case 'RA0': {$pf = array( 2437.795, 3458.268); break;} case 'RA1': {$pf = array( 1729.134, 2437.795); break;} case 'RA2': {$pf = array( 1218.898, 1729.134); break;} case 'RA3': {$pf = array( 864.567, 1218.898); break;} case 'RA4': {$pf = array( 609.449, 864.567); break;} case 'SRA0': {$pf = array( 2551.181, 3628.346); break;} case 'SRA1': {$pf = array( 1814.173, 2551.181); break;} case 'SRA2': {$pf = array( 1275.591, 1814.173); break;} case 'SRA3': {$pf = array( 907.087, 1275.591); break;} case 'SRA4': {$pf = array( 637.795, 907.087); break;} // German DIN 476 case '4A0': {$pf = array( 4767.874, 6740.787); break;} case '2A0': {$pf = array( 3370.394, 4767.874); break;} // Variations on the ISO Standard case 'A2_EXTRA' : {$pf = array( 1261.417, 1754.646); break;} case 'A3+' : {$pf = array( 932.598, 1369.134); break;} case 'A3_EXTRA' : {$pf = array( 912.756, 1261.417); break;} case 'A3_SUPER' : {$pf = array( 864.567, 1440.000); break;} case 'SUPER_A3' : {$pf = array( 864.567, 1380.472); break;} case 'A4_EXTRA' : {$pf = array( 666.142, 912.756); break;} case 'A4_SUPER' : {$pf = array( 649.134, 912.756); break;} case 'SUPER_A4' : {$pf = array( 643.465, 1009.134); break;} case 'A4_LONG' : {$pf = array( 595.276, 986.457); break;} case 'F4' : {$pf = array( 595.276, 935.433); break;} case 'SO_B5_EXTRA': {$pf = array( 572.598, 782.362); break;} case 'A5_EXTRA' : {$pf = array( 490.394, 666.142); break;} // ANSI Series case 'ANSI_E': {$pf = array( 2448.000, 3168.000); break;} case 'ANSI_D': {$pf = array( 1584.000, 2448.000); break;} case 'ANSI_C': {$pf = array( 1224.000, 1584.000); break;} case 'ANSI_B': {$pf = array( 792.000, 1224.000); break;} case 'ANSI_A': {$pf = array( 612.000, 792.000); break;} // Traditional 'Loose' North American Paper Sizes case 'USLEDGER': case 'LEDGER' : {$pf = array( 1224.000, 792.000); break;} case 'ORGANIZERK': case 'BIBLE': case 'USTABLOID': case 'TABLOID': {$pf = array( 792.000, 1224.000); break;} case 'ORGANIZERM': case 'USLETTER': case 'LETTER' : {$pf = array( 612.000, 792.000); break;} case 'USLEGAL': case 'LEGAL' : {$pf = array( 612.000, 1008.000); break;} case 'GOVERNMENTLETTER': case 'GLETTER': {$pf = array( 576.000, 756.000); break;} case 'JUNIORLEGAL': case 'JLEGAL' : {$pf = array( 576.000, 360.000); break;} // Other North American Paper Sizes case 'QUADDEMY': {$pf = array( 2520.000, 3240.000); break;} case 'SUPER_B': {$pf = array( 936.000, 1368.000); break;} case 'QUARTO': {$pf = array( 648.000, 792.000); break;} case 'GOVERNMENTLEGAL': case 'FOLIO': {$pf = array( 612.000, 936.000); break;} case 'MONARCH': case 'EXECUTIVE': {$pf = array( 522.000, 756.000); break;} case 'ORGANIZERL': case 'STATEMENT': case 'MEMO': {$pf = array( 396.000, 612.000); break;} case 'FOOLSCAP': {$pf = array( 595.440, 936.000); break;} case 'COMPACT': {$pf = array( 306.000, 486.000); break;} case 'ORGANIZERJ': {$pf = array( 198.000, 360.000); break;} // Canadian standard CAN 2-9.60M case 'P1': {$pf = array( 1587.402, 2437.795); break;} case 'P2': {$pf = array( 1218.898, 1587.402); break;} case 'P3': {$pf = array( 793.701, 1218.898); break;} case 'P4': {$pf = array( 609.449, 793.701); break;} case 'P5': {$pf = array( 396.850, 609.449); break;} case 'P6': {$pf = array( 303.307, 396.850); break;} // North American Architectural Sizes case 'ARCH_E' : {$pf = array( 2592.000, 3456.000); break;} case 'ARCH_E1': {$pf = array( 2160.000, 3024.000); break;} case 'ARCH_D' : {$pf = array( 1728.000, 2592.000); break;} case 'BROADSHEET': case 'ARCH_C' : {$pf = array( 1296.000, 1728.000); break;} case 'ARCH_B' : {$pf = array( 864.000, 1296.000); break;} case 'ARCH_A' : {$pf = array( 648.000, 864.000); break;} // --- North American Envelope Sizes --- // - Announcement Envelopes case 'ANNENV_A2' : {$pf = array( 314.640, 414.000); break;} case 'ANNENV_A6' : {$pf = array( 342.000, 468.000); break;} case 'ANNENV_A7' : {$pf = array( 378.000, 522.000); break;} case 'ANNENV_A8' : {$pf = array( 396.000, 584.640); break;} case 'ANNENV_A10' : {$pf = array( 450.000, 692.640); break;} case 'ANNENV_SLIM': {$pf = array( 278.640, 638.640); break;} // - Commercial Envelopes case 'COMMENV_N6_1/4': {$pf = array( 252.000, 432.000); break;} case 'COMMENV_N6_3/4': {$pf = array( 260.640, 468.000); break;} case 'COMMENV_N8' : {$pf = array( 278.640, 540.000); break;} case 'COMMENV_N9' : {$pf = array( 278.640, 638.640); break;} case 'COMMENV_N10' : {$pf = array( 296.640, 684.000); break;} case 'COMMENV_N11' : {$pf = array( 324.000, 746.640); break;} case 'COMMENV_N12' : {$pf = array( 342.000, 792.000); break;} case 'COMMENV_N14' : {$pf = array( 360.000, 828.000); break;} // - Catalogue Envelopes case 'CATENV_N1' : {$pf = array( 432.000, 648.000); break;} case 'CATENV_N1_3/4' : {$pf = array( 468.000, 684.000); break;} case 'CATENV_N2' : {$pf = array( 468.000, 720.000); break;} case 'CATENV_N3' : {$pf = array( 504.000, 720.000); break;} case 'CATENV_N6' : {$pf = array( 540.000, 756.000); break;} case 'CATENV_N7' : {$pf = array( 576.000, 792.000); break;} case 'CATENV_N8' : {$pf = array( 594.000, 810.000); break;} case 'CATENV_N9_1/2' : {$pf = array( 612.000, 756.000); break;} case 'CATENV_N9_3/4' : {$pf = array( 630.000, 810.000); break;} case 'CATENV_N10_1/2': {$pf = array( 648.000, 864.000); break;} case 'CATENV_N12_1/2': {$pf = array( 684.000, 900.000); break;} case 'CATENV_N13_1/2': {$pf = array( 720.000, 936.000); break;} case 'CATENV_N14_1/4': {$pf = array( 810.000, 882.000); break;} case 'CATENV_N14_1/2': {$pf = array( 828.000, 1044.000); break;} // Japanese (JIS P 0138-61) Standard B-Series case 'JIS_B0' : {$pf = array( 2919.685, 4127.244); break;} case 'JIS_B1' : {$pf = array( 2063.622, 2919.685); break;} case 'JIS_B2' : {$pf = array( 1459.843, 2063.622); break;} case 'JIS_B3' : {$pf = array( 1031.811, 1459.843); break;} case 'JIS_B4' : {$pf = array( 728.504, 1031.811); break;} case 'JIS_B5' : {$pf = array( 515.906, 728.504); break;} case 'JIS_B6' : {$pf = array( 362.835, 515.906); break;} case 'JIS_B7' : {$pf = array( 257.953, 362.835); break;} case 'JIS_B8' : {$pf = array( 181.417, 257.953); break;} case 'JIS_B9' : {$pf = array( 127.559, 181.417); break;} case 'JIS_B10': {$pf = array( 90.709, 127.559); break;} case 'JIS_B11': {$pf = array( 62.362, 90.709); break;} case 'JIS_B12': {$pf = array( 45.354, 62.362); break;} // PA Series case 'PA0' : {$pf = array( 2381.102, 3174.803,); break;} case 'PA1' : {$pf = array( 1587.402, 2381.102); break;} case 'PA2' : {$pf = array( 1190.551, 1587.402); break;} case 'PA3' : {$pf = array( 793.701, 1190.551); break;} case 'PA4' : {$pf = array( 595.276, 793.701); break;} case 'PA5' : {$pf = array( 396.850, 595.276); break;} case 'PA6' : {$pf = array( 297.638, 396.850); break;} case 'PA7' : {$pf = array( 198.425, 297.638); break;} case 'PA8' : {$pf = array( 147.402, 198.425); break;} case 'PA9' : {$pf = array( 99.213, 147.402); break;} case 'PA10': {$pf = array( 73.701, 99.213); break;} // Standard Photographic Print Sizes case 'PASSPORT_PHOTO': {$pf = array( 99.213, 127.559); break;} case 'E' : {$pf = array( 233.858, 340.157); break;} case 'L': case '3R' : {$pf = array( 252.283, 360.000); break;} case 'KG': case '4R' : {$pf = array( 289.134, 430.866); break;} case '4D' : {$pf = array( 340.157, 430.866); break;} case '2L': case '5R' : {$pf = array( 360.000, 504.567); break;} case '8P': case '6R' : {$pf = array( 430.866, 575.433); break;} case '6P': case '8R' : {$pf = array( 575.433, 720.000); break;} case '6PW': case 'S8R' : {$pf = array( 575.433, 864.567); break;} case '4P': case '10R' : {$pf = array( 720.000, 864.567); break;} case '4PW': case 'S10R': {$pf = array( 720.000, 1080.000); break;} case '11R' : {$pf = array( 790.866, 1009.134); break;} case 'S11R': {$pf = array( 790.866, 1224.567); break;} case '12R' : {$pf = array( 864.567, 1080.000); break;} case 'S12R': {$pf = array( 864.567, 1292.598); break;} // Common Newspaper Sizes case 'NEWSPAPER_BROADSHEET': {$pf = array( 2125.984, 1700.787); break;} case 'NEWSPAPER_BERLINER' : {$pf = array( 1332.283, 892.913); break;} case 'NEWSPAPER_TABLOID': case 'NEWSPAPER_COMPACT' : {$pf = array( 1218.898, 793.701); break;} // Business Cards case 'CREDIT_CARD': case 'BUSINESS_CARD': case 'BUSINESS_CARD_ISO7810': {$pf = array( 153.014, 242.646); break;} case 'BUSINESS_CARD_ISO216' : {$pf = array( 147.402, 209.764); break;} case 'BUSINESS_CARD_IT': case 'BUSINESS_CARD_UK': case 'BUSINESS_CARD_FR': case 'BUSINESS_CARD_DE': case 'BUSINESS_CARD_ES' : {$pf = array( 155.906, 240.945); break;} case 'BUSINESS_CARD_CA': case 'BUSINESS_CARD_US' : {$pf = array( 144.567, 252.283); break;} case 'BUSINESS_CARD_JP' : {$pf = array( 155.906, 257.953); break;} case 'BUSINESS_CARD_HK' : {$pf = array( 153.071, 255.118); break;} case 'BUSINESS_CARD_AU': case 'BUSINESS_CARD_DK': case 'BUSINESS_CARD_SE' : {$pf = array( 155.906, 255.118); break;} case 'BUSINESS_CARD_RU': case 'BUSINESS_CARD_CZ': case 'BUSINESS_CARD_FI': case 'BUSINESS_CARD_HU': case 'BUSINESS_CARD_IL' : {$pf = array( 141.732, 255.118); break;} // Billboards case '4SHEET' : {$pf = array( 2880.000, 4320.000); break;} case '6SHEET' : {$pf = array( 3401.575, 5102.362); break;} case '12SHEET': {$pf = array( 8640.000, 4320.000); break;} case '16SHEET': {$pf = array( 5760.000, 8640.000); break;} case '32SHEET': {$pf = array(11520.000, 8640.000); break;} case '48SHEET': {$pf = array(17280.000, 8640.000); break;} case '64SHEET': {$pf = array(23040.000, 8640.000); break;} case '96SHEET': {$pf = array(34560.000, 8640.000); break;} // Old European Sizes // - Old Imperial English Sizes case 'EN_EMPEROR' : {$pf = array( 3456.000, 5184.000); break;} case 'EN_ANTIQUARIAN' : {$pf = array( 2232.000, 3816.000); break;} case 'EN_GRAND_EAGLE' : {$pf = array( 2070.000, 3024.000); break;} case 'EN_DOUBLE_ELEPHANT' : {$pf = array( 1926.000, 2880.000); break;} case 'EN_ATLAS' : {$pf = array( 1872.000, 2448.000); break;} case 'EN_COLOMBIER' : {$pf = array( 1692.000, 2484.000); break;} case 'EN_ELEPHANT' : {$pf = array( 1656.000, 2016.000); break;} case 'EN_DOUBLE_DEMY' : {$pf = array( 1620.000, 2556.000); break;} case 'EN_IMPERIAL' : {$pf = array( 1584.000, 2160.000); break;} case 'EN_PRINCESS' : {$pf = array( 1548.000, 2016.000); break;} case 'EN_CARTRIDGE' : {$pf = array( 1512.000, 1872.000); break;} case 'EN_DOUBLE_LARGE_POST': {$pf = array( 1512.000, 2376.000); break;} case 'EN_ROYAL' : {$pf = array( 1440.000, 1800.000); break;} case 'EN_SHEET': case 'EN_HALF_POST' : {$pf = array( 1404.000, 1692.000); break;} case 'EN_SUPER_ROYAL' : {$pf = array( 1368.000, 1944.000); break;} case 'EN_DOUBLE_POST' : {$pf = array( 1368.000, 2196.000); break;} case 'EN_MEDIUM' : {$pf = array( 1260.000, 1656.000); break;} case 'EN_DEMY' : {$pf = array( 1260.000, 1620.000); break;} case 'EN_LARGE_POST' : {$pf = array( 1188.000, 1512.000); break;} case 'EN_COPY_DRAUGHT' : {$pf = array( 1152.000, 1440.000); break;} case 'EN_POST' : {$pf = array( 1116.000, 1386.000); break;} case 'EN_CROWN' : {$pf = array( 1080.000, 1440.000); break;} case 'EN_PINCHED_POST' : {$pf = array( 1062.000, 1332.000); break;} case 'EN_BRIEF' : {$pf = array( 972.000, 1152.000); break;} case 'EN_FOOLSCAP' : {$pf = array( 972.000, 1224.000); break;} case 'EN_SMALL_FOOLSCAP' : {$pf = array( 954.000, 1188.000); break;} case 'EN_POTT' : {$pf = array( 900.000, 1080.000); break;} // - Old Imperial Belgian Sizes case 'BE_GRAND_AIGLE' : {$pf = array( 1984.252, 2948.031); break;} case 'BE_COLOMBIER' : {$pf = array( 1757.480, 2409.449); break;} case 'BE_DOUBLE_CARRE': {$pf = array( 1757.480, 2607.874); break;} case 'BE_ELEPHANT' : {$pf = array( 1746.142, 2182.677); break;} case 'BE_PETIT_AIGLE' : {$pf = array( 1700.787, 2381.102); break;} case 'BE_GRAND_JESUS' : {$pf = array( 1559.055, 2069.291); break;} case 'BE_JESUS' : {$pf = array( 1530.709, 2069.291); break;} case 'BE_RAISIN' : {$pf = array( 1417.323, 1842.520); break;} case 'BE_GRAND_MEDIAN': {$pf = array( 1303.937, 1714.961); break;} case 'BE_DOUBLE_POSTE': {$pf = array( 1233.071, 1601.575); break;} case 'BE_COQUILLE' : {$pf = array( 1218.898, 1587.402); break;} case 'BE_PETIT_MEDIAN': {$pf = array( 1176.378, 1502.362); break;} case 'BE_RUCHE' : {$pf = array( 1020.472, 1303.937); break;} case 'BE_PROPATRIA' : {$pf = array( 977.953, 1218.898); break;} case 'BE_LYS' : {$pf = array( 898.583, 1125.354); break;} case 'BE_POT' : {$pf = array( 870.236, 1088.504); break;} case 'BE_ROSETTE' : {$pf = array( 765.354, 983.622); break;} // - Old Imperial French Sizes case 'FR_UNIVERS' : {$pf = array( 2834.646, 3685.039); break;} case 'FR_DOUBLE_COLOMBIER' : {$pf = array( 2551.181, 3571.654); break;} case 'FR_GRANDE_MONDE' : {$pf = array( 2551.181, 3571.654); break;} case 'FR_DOUBLE_SOLEIL' : {$pf = array( 2267.717, 3401.575); break;} case 'FR_DOUBLE_JESUS' : {$pf = array( 2154.331, 3174.803); break;} case 'FR_GRAND_AIGLE' : {$pf = array( 2125.984, 3004.724); break;} case 'FR_PETIT_AIGLE' : {$pf = array( 1984.252, 2664.567); break;} case 'FR_DOUBLE_RAISIN' : {$pf = array( 1842.520, 2834.646); break;} case 'FR_JOURNAL' : {$pf = array( 1842.520, 2664.567); break;} case 'FR_COLOMBIER_AFFICHE': {$pf = array( 1785.827, 2551.181); break;} case 'FR_DOUBLE_CAVALIER' : {$pf = array( 1757.480, 2607.874); break;} case 'FR_CLOCHE' : {$pf = array( 1700.787, 2267.717); break;} case 'FR_SOLEIL' : {$pf = array( 1700.787, 2267.717); break;} case 'FR_DOUBLE_CARRE' : {$pf = array( 1587.402, 2551.181); break;} case 'FR_DOUBLE_COQUILLE' : {$pf = array( 1587.402, 2494.488); break;} case 'FR_JESUS' : {$pf = array( 1587.402, 2154.331); break;} case 'FR_RAISIN' : {$pf = array( 1417.323, 1842.520); break;} case 'FR_CAVALIER' : {$pf = array( 1303.937, 1757.480); break;} case 'FR_DOUBLE_COURONNE' : {$pf = array( 1303.937, 2040.945); break;} case 'FR_CARRE' : {$pf = array( 1275.591, 1587.402); break;} case 'FR_COQUILLE' : {$pf = array( 1247.244, 1587.402); break;} case 'FR_DOUBLE_TELLIERE' : {$pf = array( 1247.244, 1927.559); break;} case 'FR_DOUBLE_CLOCHE' : {$pf = array( 1133.858, 1700.787); break;} case 'FR_DOUBLE_POT' : {$pf = array( 1133.858, 1757.480); break;} case 'FR_ECU' : {$pf = array( 1133.858, 1474.016); break;} case 'FR_COURONNE' : {$pf = array( 1020.472, 1303.937); break;} case 'FR_TELLIERE' : {$pf = array( 963.780, 1247.244); break;} case 'FR_POT' : {$pf = array( 878.740, 1133.858); break;} // DEFAULT ISO A4 default: {$pf = array( 595.276, 841.890); break;} } return $pf; } /** * Change the format of the current page * @param mixed $format The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() documentation or an array of two numners (width, height) or an array containing the following measures and options:<ul> * <li>['format'] = page format name (one of the above);</li> * <li>['Rotate'] : The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.</li> * <li>['PZ'] : The page's preferred zoom (magnification) factor.</li> * <li>['MediaBox'] : the boundaries of the physical medium on which the page shall be displayed or printed:</li> * <li>['MediaBox']['llx'] : lower-left x coordinate in points</li> * <li>['MediaBox']['lly'] : lower-left y coordinate in points</li> * <li>['MediaBox']['urx'] : upper-right x coordinate in points</li> * <li>['MediaBox']['ury'] : upper-right y coordinate in points</li> * <li>['CropBox'] : the visible region of default user space:</li> * <li>['CropBox']['llx'] : lower-left x coordinate in points</li> * <li>['CropBox']['lly'] : lower-left y coordinate in points</li> * <li>['CropBox']['urx'] : upper-right x coordinate in points</li> * <li>['CropBox']['ury'] : upper-right y coordinate in points</li> * <li>['BleedBox'] : the region to which the contents of the page shall be clipped when output in a production environment:</li> * <li>['BleedBox']['llx'] : lower-left x coordinate in points</li> * <li>['BleedBox']['lly'] : lower-left y coordinate in points</li> * <li>['BleedBox']['urx'] : upper-right x coordinate in points</li> * <li>['BleedBox']['ury'] : upper-right y coordinate in points</li> * <li>['TrimBox'] : the intended dimensions of the finished page after trimming:</li> * <li>['TrimBox']['llx'] : lower-left x coordinate in points</li> * <li>['TrimBox']['lly'] : lower-left y coordinate in points</li> * <li>['TrimBox']['urx'] : upper-right x coordinate in points</li> * <li>['TrimBox']['ury'] : upper-right y coordinate in points</li> * <li>['ArtBox'] : the extent of the page's meaningful content:</li> * <li>['ArtBox']['llx'] : lower-left x coordinate in points</li> * <li>['ArtBox']['lly'] : lower-left y coordinate in points</li> * <li>['ArtBox']['urx'] : upper-right x coordinate in points</li> * <li>['ArtBox']['ury'] : upper-right y coordinate in points</li> * <li>['BoxColorInfo'] :specify the colours and other visual characteristics that should be used in displaying guidelines on the screen for each of the possible page boundaries other than the MediaBox:</li> * <li>['BoxColorInfo'][BOXTYPE]['C'] : an array of three numbers in the range 0-255, representing the components in the DeviceRGB colour space.</li> * <li>['BoxColorInfo'][BOXTYPE]['W'] : the guideline width in default user units</li> * <li>['BoxColorInfo'][BOXTYPE]['S'] : the guideline style: S = Solid; D = Dashed</li> * <li>['BoxColorInfo'][BOXTYPE]['D'] : dash array defining a pattern of dashes and gaps to be used in drawing dashed guidelines</li> * <li>['trans'] : the style and duration of the visual transition to use when moving from another page to the given page during a presentation</li> * <li>['trans']['Dur'] : The page's display duration (also called its advance timing): the maximum length of time, in seconds, that the page shall be displayed during presentations before the viewer application shall automatically advance to the next page.</li> * <li>['trans']['S'] : transition style : Split, Blinds, Box, Wipe, Dissolve, Glitter, R, Fly, Push, Cover, Uncover, Fade</li> * <li>['trans']['D'] : The duration of the transition effect, in seconds.</li> * <li>['trans']['Dm'] : (Split and Blinds transition styles only) The dimension in which the specified transition effect shall occur: H = Horizontal, V = Vertical. Default value: H.</li> * <li>['trans']['M'] : (Split, Box and Fly transition styles only) The direction of motion for the specified transition effect: I = Inward from the edges of the page, O = Outward from the center of the pageDefault value: I.</li> * <li>['trans']['Di'] : (Wipe, Glitter, Fly, Cover, Uncover and Push transition styles only) The direction in which the specified transition effect shall moves, expressed in degrees counterclockwise starting from a left-to-right direction. If the value is a number, it shall be one of: 0 = Left to right, 90 = Bottom to top (Wipe only), 180 = Right to left (Wipe only), 270 = Top to bottom, 315 = Top-left to bottom-right (Glitter only). If the value is a name, it shall be None, which is relevant only for the Fly transition when the value of SS is not 1.0. Default value: 0.</li> * <li>['trans']['SS'] : (Fly transition style only) The starting or ending scale at which the changes shall be drawn. If M specifies an inward transition, the scale of the changes drawn shall progress from SS to 1.0 over the course of the transition. If M specifies an outward transition, the scale of the changes drawn shall progress from 1.0 to SS over the course of the transition. Default: 1.0.</li> * <li>['trans']['B'] : (Fly transition style only) If true, the area that shall be flown in is rectangular and opaque. Default: false.</li> * </ul> * @param string $orientation page orientation. Possible values are (case insensitive):<ul> * <li>P or Portrait (default)</li> * <li>L or Landscape</li> * <li>'' (empty string) for automatic orientation</li> * </ul> * @access protected * @since 3.0.015 (2008-06-06) * @see getPageSizeFromFormat() */ protected function setPageFormat($format, $orientation='P') { if (!empty($format) AND isset($this->pagedim[$this->page])) { // remove inherited values unset($this->pagedim[$this->page]); } if (is_string($format)) { // get page measures from format name $pf = $this->getPageSizeFromFormat($format); $this->fwPt = $pf[0]; $this->fhPt = $pf[1]; } else { // the boundaries of the physical medium on which the page shall be displayed or printed if (isset($format['MediaBox'])) { $this->setPageBoxes($this->page, 'MediaBox', $format['MediaBox']['llx'], $format['MediaBox']['lly'], $format['MediaBox']['urx'], $format['MediaBox']['ury'], false); $this->fwPt = (($format['MediaBox']['urx'] - $format['MediaBox']['llx']) * $this->k); $this->fhPt = (($format['MediaBox']['ury'] - $format['MediaBox']['lly']) * $this->k); } else { if (isset($format[0]) AND is_numeric($format[0]) AND isset($format[1]) AND is_numeric($format[1])) { $pf = array(($format[0] * $this->k), ($format[1] * $this->k)); } else { if (!isset($format['format'])) { // default value $format['format'] = 'A4'; } $pf = $this->getPageSizeFromFormat($format['format']); } $this->fwPt = $pf[0]; $this->fhPt = $pf[1]; $this->setPageBoxes($this->page, 'MediaBox', 0, 0, $this->fwPt, $this->fhPt, true); } // the visible region of default user space if (isset($format['CropBox'])) { $this->setPageBoxes($this->page, 'CropBox', $format['CropBox']['llx'], $format['CropBox']['lly'], $format['CropBox']['urx'], $format['CropBox']['ury'], false); } // the region to which the contents of the page shall be clipped when output in a production environment if (isset($format['BleedBox'])) { $this->setPageBoxes($this->page, 'BleedBox', $format['BleedBox']['llx'], $format['BleedBox']['lly'], $format['BleedBox']['urx'], $format['BleedBox']['ury'], false); } // the intended dimensions of the finished page after trimming if (isset($format['TrimBox'])) { $this->setPageBoxes($this->page, 'TrimBox', $format['TrimBox']['llx'], $format['TrimBox']['lly'], $format['TrimBox']['urx'], $format['TrimBox']['ury'], false); } // the page's meaningful content (including potential white space) if (isset($format['ArtBox'])) { $this->setPageBoxes($this->page, 'ArtBox', $format['ArtBox']['llx'], $format['ArtBox']['lly'], $format['ArtBox']['urx'], $format['ArtBox']['ury'], false); } // specify the colours and other visual characteristics that should be used in displaying guidelines on the screen for the various page boundaries if (isset($format['BoxColorInfo'])) { $this->pagedim[$this->page]['BoxColorInfo'] = $format['BoxColorInfo']; } if (isset($format['Rotate']) AND (($format['Rotate'] % 90) == 0)) { // The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90. $this->pagedim[$this->page]['Rotate'] = intval($format['Rotate']); } if (isset($format['PZ'])) { // The page's preferred zoom (magnification) factor $this->pagedim[$this->page]['PZ'] = floatval($format['PZ']); } if (isset($format['trans'])) { // The style and duration of the visual transition to use when moving from another page to the given page during a presentation if (isset($format['trans']['Dur'])) { // The page's display duration $this->pagedim[$this->page]['trans']['Dur'] = floatval($format['trans']['Dur']); } $stansition_styles = array('Split', 'Blinds', 'Box', 'Wipe', 'Dissolve', 'Glitter', 'R', 'Fly', 'Push', 'Cover', 'Uncover', 'Fade'); if (isset($format['trans']['S']) AND in_array($format['trans']['S'], $stansition_styles)) { // The transition style that shall be used when moving to this page from another during a presentation $this->pagedim[$this->page]['trans']['S'] = $format['trans']['S']; $valid_effect = array('Split', 'Blinds'); $valid_vals = array('H', 'V'); if (isset($format['trans']['Dm']) AND in_array($format['trans']['S'], $valid_effect) AND in_array($format['trans']['Dm'], $valid_vals)) { $this->pagedim[$this->page]['trans']['Dm'] = $format['trans']['Dm']; } $valid_effect = array('Split', 'Box', 'Fly'); $valid_vals = array('I', 'O'); if (isset($format['trans']['M']) AND in_array($format['trans']['S'], $valid_effect) AND in_array($format['trans']['M'], $valid_vals)) { $this->pagedim[$this->page]['trans']['M'] = $format['trans']['M']; } $valid_effect = array('Wipe', 'Glitter', 'Fly', 'Cover', 'Uncover', 'Push'); if (isset($format['trans']['Di']) AND in_array($format['trans']['S'], $valid_effect)) { if (((($format['trans']['Di'] == 90) OR ($format['trans']['Di'] == 180)) AND ($format['trans']['S'] == 'Wipe')) OR (($format['trans']['Di'] == 315) AND ($format['trans']['S'] == 'Glitter')) OR (($format['trans']['Di'] == 0) OR ($format['trans']['Di'] == 270))) { $this->pagedim[$this->page]['trans']['Di'] = intval($format['trans']['Di']); } } if (isset($format['trans']['SS']) AND ($format['trans']['S'] == 'Fly')) { $this->pagedim[$this->page]['trans']['SS'] = floatval($format['trans']['SS']); } if (isset($format['trans']['B']) AND ($format['trans']['B'] === true) AND ($format['trans']['S'] == 'Fly')) { $this->pagedim[$this->page]['trans']['B'] = 'true'; } } else { $this->pagedim[$this->page]['trans']['S'] = 'R'; } if (isset($format['trans']['D'])) { // The duration of the transition effect, in seconds $this->pagedim[$this->page]['trans']['D'] = floatval($format['trans']['D']); } else { $this->pagedim[$this->page]['trans']['D'] = 1; } } } $this->setPageOrientation($orientation); } /** * Set page boundaries. * @param int $page page number * @param string $type valid values are: <ul><li>'MediaBox' : the boundaries of the physical medium on which the page shall be displayed or printed;</li><li>'CropBox' : the visible region of default user space;</li><li>'BleedBox' : the region to which the contents of the page shall be clipped when output in a production environment;</li><li>'TrimBox' : the intended dimensions of the finished page after trimming;</li><li>'ArtBox' : the page's meaningful content (including potential white space).</li></ul> * @param float $llx lower-left x coordinate in user units * @param float $lly lower-left y coordinate in user units * @param float $urx upper-right x coordinate in user units * @param float $ury upper-right y coordinate in user units * @param boolean $points if true uses user units as unit of measure, otherwise uses PDF points * @access public * @since 5.0.010 (2010-05-17) */ public function setPageBoxes($page, $type, $llx, $lly, $urx, $ury, $points=false) { if (!isset($this->pagedim[$page])) { // initialize array $this->pagedim[$page] = array(); } $pageboxes = array('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox'); if (!in_array($type, $pageboxes)) { return; } if ($points) { $k = 1; } else { $k = $this->k; } $this->pagedim[$page][$type]['llx'] = ($llx * $k); $this->pagedim[$page][$type]['lly'] = ($lly * $k); $this->pagedim[$page][$type]['urx'] = ($urx * $k); $this->pagedim[$page][$type]['ury'] = ($ury * $k); } /** * Swap X and Y coordinates of page boxes (change page boxes orientation). * @param int $page page number * @access protected * @since 5.0.010 (2010-05-17) */ protected function swapPageBoxCoordinates($page) { $pageboxes = array('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox'); foreach ($pageboxes as $type) { // swap X and Y coordinates if (isset($this->pagedim[$page][$type])) { $tmp = $this->pagedim[$page][$type]['llx']; $this->pagedim[$page][$type]['llx'] = $this->pagedim[$page][$type]['lly']; $this->pagedim[$page][$type]['lly'] = $tmp; $tmp = $this->pagedim[$page][$type]['urx']; $this->pagedim[$page][$type]['urx'] = $this->pagedim[$page][$type]['ury']; $this->pagedim[$page][$type]['ury'] = $tmp; } } } /** * Set page orientation. * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or Portrait (default)</li><li>L or Landscape</li><li>'' (empty string) for automatic orientation</li></ul> * @param boolean $autopagebreak Boolean indicating if auto-page-break mode should be on or off. * @param float $bottommargin bottom margin of the page. * @access public * @since 3.0.015 (2008-06-06) */ public function setPageOrientation($orientation, $autopagebreak='', $bottommargin='') { if (!isset($this->pagedim[$this->page]['MediaBox'])) { // the boundaries of the physical medium on which the page shall be displayed or printed $this->setPageBoxes($this->page, 'MediaBox', 0, 0, $this->fwPt, $this->fhPt, true); } if (!isset($this->pagedim[$this->page]['CropBox'])) { // the visible region of default user space $this->setPageBoxes($this->page, 'CropBox', $this->pagedim[$this->page]['MediaBox']['llx'], $this->pagedim[$this->page]['MediaBox']['lly'], $this->pagedim[$this->page]['MediaBox']['urx'], $this->pagedim[$this->page]['MediaBox']['ury'], true); } if (!isset($this->pagedim[$this->page]['BleedBox'])) { // the region to which the contents of the page shall be clipped when output in a production environment $this->setPageBoxes($this->page, 'BleedBox', $this->pagedim[$this->page]['CropBox']['llx'], $this->pagedim[$this->page]['CropBox']['lly'], $this->pagedim[$this->page]['CropBox']['urx'], $this->pagedim[$this->page]['CropBox']['ury'], true); } if (!isset($this->pagedim[$this->page]['TrimBox'])) { // the intended dimensions of the finished page after trimming $this->setPageBoxes($this->page, 'TrimBox', $this->pagedim[$this->page]['CropBox']['llx'], $this->pagedim[$this->page]['CropBox']['lly'], $this->pagedim[$this->page]['CropBox']['urx'], $this->pagedim[$this->page]['CropBox']['ury'], true); } if (!isset($this->pagedim[$this->page]['ArtBox'])) { // the page's meaningful content (including potential white space) $this->setPageBoxes($this->page, 'ArtBox', $this->pagedim[$this->page]['CropBox']['llx'], $this->pagedim[$this->page]['CropBox']['lly'], $this->pagedim[$this->page]['CropBox']['urx'], $this->pagedim[$this->page]['CropBox']['ury'], true); } if (!isset($this->pagedim[$this->page]['Rotate'])) { // The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90. $this->pagedim[$this->page]['Rotate'] = 0; } if (!isset($this->pagedim[$this->page]['PZ'])) { // The page's preferred zoom (magnification) factor $this->pagedim[$this->page]['PZ'] = 1; } if ($this->fwPt > $this->fhPt) { // landscape $default_orientation = 'L'; } else { // portrait $default_orientation = 'P'; } $valid_orientations = array('P', 'L'); if (empty($orientation)) { $orientation = $default_orientation; } else { $orientation = strtoupper($orientation{0}); } if (in_array($orientation, $valid_orientations) AND ($orientation != $default_orientation)) { $this->CurOrientation = $orientation; $this->wPt = $this->fhPt; $this->hPt = $this->fwPt; } else { $this->CurOrientation = $default_orientation; $this->wPt = $this->fwPt; $this->hPt = $this->fhPt; } if ((abs($this->pagedim[$this->page]['MediaBox']['urx'] - $this->hPt) < $this->feps) AND (abs($this->pagedim[$this->page]['MediaBox']['ury'] - $this->wPt) < $this->feps)){ // swap X and Y coordinates (change page orientation) $this->swapPageBoxCoordinates($this->page); } $this->w = $this->wPt / $this->k; $this->h = $this->hPt / $this->k; if ($this->empty_string($autopagebreak)) { if (isset($this->AutoPageBreak)) { $autopagebreak = $this->AutoPageBreak; } else { $autopagebreak = true; } } if ($this->empty_string($bottommargin)) { if (isset($this->bMargin)) { $bottommargin = $this->bMargin; } else { // default value = 2 cm $bottommargin = 2 * 28.35 / $this->k; } } $this->SetAutoPageBreak($autopagebreak, $bottommargin); // store page dimensions $this->pagedim[$this->page]['w'] = $this->wPt; $this->pagedim[$this->page]['h'] = $this->hPt; $this->pagedim[$this->page]['wk'] = $this->w; $this->pagedim[$this->page]['hk'] = $this->h; $this->pagedim[$this->page]['tm'] = $this->tMargin; $this->pagedim[$this->page]['bm'] = $bottommargin; $this->pagedim[$this->page]['lm'] = $this->lMargin; $this->pagedim[$this->page]['rm'] = $this->rMargin; $this->pagedim[$this->page]['pb'] = $autopagebreak; $this->pagedim[$this->page]['or'] = $this->CurOrientation; $this->pagedim[$this->page]['olm'] = $this->original_lMargin; $this->pagedim[$this->page]['orm'] = $this->original_rMargin; } /** * Set regular expression to detect withespaces or word separators. * The pattern delimiter must be the forward-slash character '/'. * Some example patterns are: * <pre> * Non-Unicode or missing PCRE unicode support: '/[^\S\xa0]/' * Unicode and PCRE unicode support: '/[^\S\P{Z}\xa0]/u' * Unicode and PCRE unicode support in Chinese mode: '/[^\S\P{Z}\P{Lo}\xa0]/u' * if PCRE unicode support is turned ON (\P is the negate class of \p): * \p{Z} or \p{Separator}: any kind of Unicode whitespace or invisible separator. * \p{Lo} or \p{Other_Letter}: a Unicode letter or ideograph that does not have lowercase and uppercase variants. * \p{Lo} is needed for Chinese characters because are packed next to each other without spaces in between. * </pre> * @param string $re regular expression (leave empty for default). * @access public * @since 4.6.016 (2009-06-15) */ public function setSpacesRE($re='/[^\S\xa0]/') { $this->re_spaces = $re; $re_parts = explode('/', $re); // get pattern parts $this->re_space = array(); if (isset($re_parts[1]) AND !empty($re_parts[1])) { $this->re_space['p'] = $re_parts[1]; } else { $this->re_space['p'] = '[\s]'; } // set pattern modifiers if (isset($re_parts[2]) AND !empty($re_parts[2])) { $this->re_space['m'] = $re_parts[2]; } else { $this->re_space['m'] = ''; } } /** * Enable or disable Right-To-Left language mode * @param Boolean $enable if true enable Right-To-Left language mode. * @param Boolean $resetx if true reset the X position on direction change. * @access public * @since 2.0.000 (2008-01-03) */ public function setRTL($enable, $resetx=true) { $enable = $enable ? true : false; $resetx = ($resetx AND ($enable != $this->rtl)); $this->rtl = $enable; $this->tmprtl = false; if ($resetx) { $this->Ln(0); } } /** * Return the RTL status * @return boolean * @access public * @since 4.0.012 (2008-07-24) */ public function getRTL() { return $this->rtl; } /** * Force temporary RTL language direction * @param mixed $mode can be false, 'L' for LTR or 'R' for RTL * @access public * @since 2.1.000 (2008-01-09) */ public function setTempRTL($mode) { $newmode = false; switch ($mode) { case 'ltr': case 'LTR': case 'L': { if ($this->rtl) { $newmode = 'L'; } break; } case 'rtl': case 'RTL': case 'R': { if (!$this->rtl) { $newmode = 'R'; } break; } case false: default: { $newmode = false; break; } } $this->tmprtl = $newmode; } /** * Return the current temporary RTL status * @return boolean * @access public * @since 4.8.014 (2009-11-04) */ public function isRTLTextDir() { return ($this->rtl OR ($this->tmprtl == 'R')); } /** * Set the last cell height. * @param float $h cell height. * @author Nicola Asuni * @access public * @since 1.53.0.TC034 */ public function setLastH($h) { $this->lasth = $h; } /** * Get the last cell height. * @return last cell height * @access public * @since 4.0.017 (2008-08-05) */ public function getLastH() { return $this->lasth; } /** * Set the adjusting factor to convert pixels to user units. * @param float $scale adjusting factor to convert pixels to user units. * @author Nicola Asuni * @access public * @since 1.5.2 */ public function setImageScale($scale) { $this->imgscale = $scale; } /** * Returns the adjusting factor to convert pixels to user units. * @return float adjusting factor to convert pixels to user units. * @author Nicola Asuni * @access public * @since 1.5.2 */ public function getImageScale() { return $this->imgscale; } /** * Returns an array of page dimensions: * <ul><li>$this->pagedim[$this->page]['w'] = page width in points</li><li>$this->pagedim[$this->page]['h'] = height in points</li><li>$this->pagedim[$this->page]['wk'] = page width in user units</li><li>$this->pagedim[$this->page]['hk'] = page height in user units</li><li>$this->pagedim[$this->page]['tm'] = top margin</li><li>$this->pagedim[$this->page]['bm'] = bottom margin</li><li>$this->pagedim[$this->page]['lm'] = left margin</li><li>$this->pagedim[$this->page]['rm'] = right margin</li><li>$this->pagedim[$this->page]['pb'] = auto page break</li><li>$this->pagedim[$this->page]['or'] = page orientation</li><li>$this->pagedim[$this->page]['olm'] = original left margin</li><li>$this->pagedim[$this->page]['orm'] = original right margin</li><li>$this->pagedim[$this->page]['Rotate'] = The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.</li><li>$this->pagedim[$this->page]['PZ'] = The page's preferred zoom (magnification) factor.</li><li>$this->pagedim[$this->page]['trans'] : the style and duration of the visual transition to use when moving from another page to the given page during a presentation<ul><li>$this->pagedim[$this->page]['trans']['Dur'] = The page's display duration (also called its advance timing): the maximum length of time, in seconds, that the page shall be displayed during presentations before the viewer application shall automatically advance to the next page.</li><li>$this->pagedim[$this->page]['trans']['S'] = transition style : Split, Blinds, Box, Wipe, Dissolve, Glitter, R, Fly, Push, Cover, Uncover, Fade</li><li>$this->pagedim[$this->page]['trans']['D'] = The duration of the transition effect, in seconds.</li><li>$this->pagedim[$this->page]['trans']['Dm'] = (Split and Blinds transition styles only) The dimension in which the specified transition effect shall occur: H = Horizontal, V = Vertical. Default value: H.</li><li>$this->pagedim[$this->page]['trans']['M'] = (Split, Box and Fly transition styles only) The direction of motion for the specified transition effect: I = Inward from the edges of the page, O = Outward from the center of the pageDefault value: I.</li><li>$this->pagedim[$this->page]['trans']['Di'] = (Wipe, Glitter, Fly, Cover, Uncover and Push transition styles only) The direction in which the specified transition effect shall moves, expressed in degrees counterclockwise starting from a left-to-right direction. If the value is a number, it shall be one of: 0 = Left to right, 90 = Bottom to top (Wipe only), 180 = Right to left (Wipe only), 270 = Top to bottom, 315 = Top-left to bottom-right (Glitter only). If the value is a name, it shall be None, which is relevant only for the Fly transition when the value of SS is not 1.0. Default value: 0.</li><li>$this->pagedim[$this->page]['trans']['SS'] = (Fly transition style only) The starting or ending scale at which the changes shall be drawn. If M specifies an inward transition, the scale of the changes drawn shall progress from SS to 1.0 over the course of the transition. If M specifies an outward transition, the scale of the changes drawn shall progress from 1.0 to SS over the course of the transition. Default: 1.0. </li><li>$this->pagedim[$this->page]['trans']['B'] = (Fly transition style only) If true, the area that shall be flown in is rectangular and opaque. Default: false.</li></ul></li><li>$this->pagedim[$this->page]['MediaBox'] : the boundaries of the physical medium on which the page shall be displayed or printed<ul><li>$this->pagedim[$this->page]['MediaBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['MediaBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['MediaBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['MediaBox']['ury'] = upper-right y coordinate in points</li></ul></li><li>$this->pagedim[$this->page]['CropBox'] : the visible region of default user space<ul><li>$this->pagedim[$this->page]['CropBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['CropBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['CropBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['CropBox']['ury'] = upper-right y coordinate in points</li></ul></li><li>$this->pagedim[$this->page]['BleedBox'] : the region to which the contents of the page shall be clipped when output in a production environment<ul><li>$this->pagedim[$this->page]['BleedBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['BleedBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['BleedBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['BleedBox']['ury'] = upper-right y coordinate in points</li></ul></li><li>$this->pagedim[$this->page]['TrimBox'] : the intended dimensions of the finished page after trimming<ul><li>$this->pagedim[$this->page]['TrimBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['TrimBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['TrimBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['TrimBox']['ury'] = upper-right y coordinate in points</li></ul></li><li>$this->pagedim[$this->page]['ArtBox'] : the extent of the page's meaningful content<ul><li>$this->pagedim[$this->page]['ArtBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['ArtBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['ArtBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['ArtBox']['ury'] = upper-right y coordinate in points</li></ul></li></ul> * @param int $pagenum page number (empty = current page) * @return array of page dimensions. * @author Nicola Asuni * @access public * @since 4.5.027 (2009-03-16) */ public function getPageDimensions($pagenum='') { if (empty($pagenum)) { $pagenum = $this->page; } return $this->pagedim[$pagenum]; } /** * Returns the page width in units. * @param int $pagenum page number (empty = current page) * @return int page width. * @author Nicola Asuni * @access public * @since 1.5.2 * @see getPageDimensions() */ public function getPageWidth($pagenum='') { if (empty($pagenum)) { return $this->w; } return $this->pagedim[$pagenum]['w']; } /** * Returns the page height in units. * @param int $pagenum page number (empty = current page) * @return int page height. * @author Nicola Asuni * @access public * @since 1.5.2 * @see getPageDimensions() */ public function getPageHeight($pagenum='') { if (empty($pagenum)) { return $this->h; } return $this->pagedim[$pagenum]['h']; } /** * Returns the page break margin. * @param int $pagenum page number (empty = current page) * @return int page break margin. * @author Nicola Asuni * @access public * @since 1.5.2 * @see getPageDimensions() */ public function getBreakMargin($pagenum='') { if (empty($pagenum)) { return $this->bMargin; } return $this->pagedim[$pagenum]['bm']; } /** * Returns the scale factor (number of points in user unit). * @return int scale factor. * @author Nicola Asuni * @access public * @since 1.5.2 */ public function getScaleFactor() { return $this->k; } /** * Defines the left, top and right margins. * @param float $left Left margin. * @param float $top Top margin. * @param float $right Right margin. Default value is the left one. * @param boolean $keepmargins if true overwrites the default page margins * @access public * @since 1.0 * @see SetLeftMargin(), SetTopMargin(), SetRightMargin(), SetAutoPageBreak() */ public function SetMargins($left, $top, $right=-1, $keepmargins=false) { //Set left, top and right margins $this->lMargin = $left; $this->tMargin = $top; if ($right == -1) { $right = $left; } $this->rMargin = $right; if ($keepmargins) { // overwrite original values $this->original_lMargin = $this->lMargin; $this->original_rMargin = $this->rMargin; } } /** * Defines the left margin. The method can be called before creating the first page. If the current abscissa gets out of page, it is brought back to the margin. * @param float $margin The margin. * @access public * @since 1.4 * @see SetTopMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins() */ public function SetLeftMargin($margin) { //Set left margin $this->lMargin = $margin; if (($this->page > 0) AND ($this->x < $margin)) { $this->x = $margin; } } /** * Defines the top margin. The method can be called before creating the first page. * @param float $margin The margin. * @access public * @since 1.5 * @see SetLeftMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins() */ public function SetTopMargin($margin) { //Set top margin $this->tMargin = $margin; if (($this->page > 0) AND ($this->y < $margin)) { $this->y = $margin; } } /** * Defines the right margin. The method can be called before creating the first page. * @param float $margin The margin. * @access public * @since 1.5 * @see SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins() */ public function SetRightMargin($margin) { $this->rMargin = $margin; if (($this->page > 0) AND ($this->x > ($this->w - $margin))) { $this->x = $this->w - $margin; } } /** * Set the internal Cell padding. * @param float $pad internal padding. * @access public * @since 2.1.000 (2008-01-09) * @see Cell(), SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins() */ public function SetCellPadding($pad) { $this->cMargin = $pad; } /** * Enables or disables the automatic page breaking mode. When enabling, the second parameter is the distance from the bottom of the page that defines the triggering limit. By default, the mode is on and the margin is 2 cm. * @param boolean $auto Boolean indicating if mode should be on or off. * @param float $margin Distance from the bottom of the page. * @access public * @since 1.0 * @see Cell(), MultiCell(), AcceptPageBreak() */ public function SetAutoPageBreak($auto, $margin=0) { //Set auto page break mode and triggering margin $this->AutoPageBreak = $auto; $this->bMargin = $margin; $this->PageBreakTrigger = $this->h - $margin; } /** * Defines the way the document is to be displayed by the viewer. * @param mixed $zoom The zoom to use. It can be one of the following string values or a number indicating the zooming factor to use. <ul><li>fullpage: displays the entire page on screen </li><li>fullwidth: uses maximum width of window</li><li>real: uses real size (equivalent to 100% zoom)</li><li>default: uses viewer default mode</li></ul> * @param string $layout The page layout. Possible values are:<ul><li>SinglePage Display one page at a time</li><li>OneColumn Display the pages in one column</li><li>TwoColumnLeft Display the pages in two columns, with odd-numbered pages on the left</li><li>TwoColumnRight Display the pages in two columns, with odd-numbered pages on the right</li><li>TwoPageLeft (PDF 1.5) Display the pages two at a time, with odd-numbered pages on the left</li><li>TwoPageRight (PDF 1.5) Display the pages two at a time, with odd-numbered pages on the right</li></ul> * @param string $mode A name object specifying how the document should be displayed when opened:<ul><li>UseNone Neither document outline nor thumbnail images visible</li><li>UseOutlines Document outline visible</li><li>UseThumbs Thumbnail images visible</li><li>FullScreen Full-screen mode, with no menu bar, window controls, or any other window visible</li><li>UseOC (PDF 1.5) Optional content group panel visible</li><li>UseAttachments (PDF 1.6) Attachments panel visible</li></ul> * @access public * @since 1.2 */ public function SetDisplayMode($zoom, $layout='SinglePage', $mode='UseNone') { //Set display mode in viewer if (($zoom == 'fullpage') OR ($zoom == 'fullwidth') OR ($zoom == 'real') OR ($zoom == 'default') OR (!is_string($zoom))) { $this->ZoomMode = $zoom; } else { $this->Error('Incorrect zoom display mode: '.$zoom); } switch ($layout) { case 'default': case 'single': case 'SinglePage': { $this->LayoutMode = 'SinglePage'; break; } case 'continuous': case 'OneColumn': { $this->LayoutMode = 'OneColumn'; break; } case 'two': case 'TwoColumnLeft': { $this->LayoutMode = 'TwoColumnLeft'; break; } case 'TwoColumnRight': { $this->LayoutMode = 'TwoColumnRight'; break; } case 'TwoPageLeft': { $this->LayoutMode = 'TwoPageLeft'; break; } case 'TwoPageRight': { $this->LayoutMode = 'TwoPageRight'; break; } default: { $this->LayoutMode = 'SinglePage'; } } switch ($mode) { case 'UseNone': { $this->PageMode = 'UseNone'; break; } case 'UseOutlines': { $this->PageMode = 'UseOutlines'; break; } case 'UseThumbs': { $this->PageMode = 'UseThumbs'; break; } case 'FullScreen': { $this->PageMode = 'FullScreen'; break; } case 'UseOC': { $this->PageMode = 'UseOC'; break; } case '': { $this->PageMode = 'UseAttachments'; break; } default: { $this->PageMode = 'UseNone'; } } } /** * Activates or deactivates page compression. When activated, the internal representation of each page is compressed, which leads to a compression ratio of about 2 for the resulting document. Compression is on by default. * Note: the Zlib extension is required for this feature. If not present, compression will be turned off. * @param boolean $compress Boolean indicating if compression must be enabled. * @access public * @since 1.4 */ public function SetCompression($compress) { //Set page compression if (function_exists('gzcompress')) { $this->compress = $compress ? true : false; } else { $this->compress = false; } } /** * Defines the title of the document. * @param string $title The title. * @access public * @since 1.2 * @see SetAuthor(), SetCreator(), SetKeywords(), SetSubject() */ public function SetTitle($title) { //Title of document $this->title = $title; } /** * Defines the subject of the document. * @param string $subject The subject. * @access public * @since 1.2 * @see SetAuthor(), SetCreator(), SetKeywords(), SetTitle() */ public function SetSubject($subject) { //Subject of document $this->subject = $subject; } /** * Defines the author of the document. * @param string $author The name of the author. * @access public * @since 1.2 * @see SetCreator(), SetKeywords(), SetSubject(), SetTitle() */ public function SetAuthor($author) { //Author of document $this->author = $author; } /** * Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'. * @param string $keywords The list of keywords. * @access public * @since 1.2 * @see SetAuthor(), SetCreator(), SetSubject(), SetTitle() */ public function SetKeywords($keywords) { //Keywords of document $this->keywords = $keywords; } /** * Defines the creator of the document. This is typically the name of the application that generates the PDF. * @param string $creator The name of the creator. * @access public * @since 1.2 * @see SetAuthor(), SetKeywords(), SetSubject(), SetTitle() */ public function SetCreator($creator) { //Creator of document $this->creator = $creator; } /** * This method is automatically called in case of fatal error; it simply outputs the message and halts the execution. An inherited class may override it to customize the error handling but should always halt the script, or the resulting document would probably be invalid. * 2004-06-11 :: Nicola Asuni : changed bold tag with strong * @param string $msg The error message * @access public * @since 1.0 */ public function Error($msg) { // unset all class variables $this->_destroy(true); // exit program and print error die('<strong>TCPDF ERROR: </strong>'.$msg); } /** * This method begins the generation of the PDF document. * It is not necessary to call it explicitly because AddPage() does it automatically. * Note: no page is created by this method * @access public * @since 1.0 * @see AddPage(), Close() */ public function Open() { //Begin document $this->state = 1; } /** * Terminates the PDF document. * It is not necessary to call this method explicitly because Output() does it automatically. * If the document contains no page, AddPage() is called to prevent from getting an invalid document. * @access public * @since 1.0 * @see Open(), Output() */ public function Close() { if ($this->state == 3) { return; } if ($this->page == 0) { $this->AddPage(); } // save current graphic settings $gvars = $this->getGraphicVars(); $this->lastpage(true); $this->SetAutoPageBreak(false); $this->x = 0; $this->y = $this->h - (1 / $this->k); $this->lMargin = 0; $this->_out('q'); $this->setVisibility('screen'); $this->SetFont('helvetica', '', 1); $this->SetTextColor(255, 255, 255); $msg = "\x50\x6f\x77\x65\x72\x65\x64\x20\x62\x79\x20\x54\x43\x50\x44\x46\x20\x28\x77\x77\x77\x2e\x74\x63\x70\x64\x66\x2e\x6f\x72\x67\x29"; $lnk = "\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x74\x63\x70\x64\x66\x2e\x6f\x72\x67"; $this->Cell(0, 0, $msg, 0, 0, 'L', 0, $lnk, 0, false, 'D', 'B'); $this->setVisibility('all'); $this->_out('Q'); // restore graphic settings $this->setGraphicVars($gvars); // close page $this->endPage(); // close document $this->_enddoc(); // unset all class variables (except critical ones) $this->_destroy(false); } /** * Move pointer at the specified document page and update page dimensions. * @param int $pnum page number (1 ... numpages) * @param boolean $resetmargins if true reset left, right, top margins and Y position. * @access public * @since 2.1.000 (2008-01-07) * @see getPage(), lastpage(), getNumPages() */ public function setPage($pnum, $resetmargins=false) { if (($pnum == $this->page) AND ($this->state == 2)) { return; } if (($pnum > 0) AND ($pnum <= $this->numpages)) { $this->state = 2; // save current graphic settings //$gvars = $this->getGraphicVars(); $oldpage = $this->page; $this->page = $pnum; $this->wPt = $this->pagedim[$this->page]['w']; $this->hPt = $this->pagedim[$this->page]['h']; $this->w = $this->pagedim[$this->page]['wk']; $this->h = $this->pagedim[$this->page]['hk']; $this->tMargin = $this->pagedim[$this->page]['tm']; $this->bMargin = $this->pagedim[$this->page]['bm']; $this->original_lMargin = $this->pagedim[$this->page]['olm']; $this->original_rMargin = $this->pagedim[$this->page]['orm']; $this->AutoPageBreak = $this->pagedim[$this->page]['pb']; $this->CurOrientation = $this->pagedim[$this->page]['or']; $this->SetAutoPageBreak($this->AutoPageBreak, $this->bMargin); // restore graphic settings //$this->setGraphicVars($gvars); if ($resetmargins) { $this->lMargin = $this->pagedim[$this->page]['olm']; $this->rMargin = $this->pagedim[$this->page]['orm']; $this->SetY($this->tMargin); } else { // account for booklet mode if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) { $deltam = $this->pagedim[$this->page]['olm'] - $this->pagedim[$this->page]['orm']; $this->lMargin += $deltam; $this->rMargin -= $deltam; } } } else { $this->Error('Wrong page number on setPage() function: '.$pnum); } } /** * Reset pointer to the last document page. * @param boolean $resetmargins if true reset left, right, top margins and Y position. * @access public * @since 2.0.000 (2008-01-04) * @see setPage(), getPage(), getNumPages() */ public function lastPage($resetmargins=false) { $this->setPage($this->getNumPages(), $resetmargins); } /** * Get current document page number. * @return int page number * @access public * @since 2.1.000 (2008-01-07) * @see setPage(), lastpage(), getNumPages() */ public function getPage() { return $this->page; } /** * Get the total number of insered pages. * @return int number of pages * @access public * @since 2.1.000 (2008-01-07) * @see setPage(), getPage(), lastpage() */ public function getNumPages() { return $this->numpages; } /** * Adds a new TOC (Table Of Content) page to the document. * @param string $orientation page orientation. * @param boolean $keepmargins if true overwrites the default page margins with the current margins * @access public * @since 5.0.001 (2010-05-06) * @see AddPage(), startPage(), endPage(), endTOCPage() */ public function addTOCPage($orientation='', $format='', $keepmargins=false) { $this->AddPage($orientation, $format, $keepmargins, true); } /** * Terminate the current TOC (Table Of Content) page * @access public * @since 5.0.001 (2010-05-06) * @see AddPage(), startPage(), endPage(), addTOCPage() */ public function endTOCPage() { $this->endPage(true); } /** * Adds a new page to the document. If a page is already present, the Footer() method is called first to output the footer (if enabled). Then the page is added, the current position set to the top-left corner according to the left and top margins (or top-right if in RTL mode), and Header() is called to display the header (if enabled). * The origin of the coordinate system is at the top-left corner (or top-right for RTL) and increasing ordinates go downwards. * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul> * @param mixed $format The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() or an array of parameters specified at setPageFormat(). * @param boolean $keepmargins if true overwrites the default page margins with the current margins * @param boolean $tocpage if true set the tocpage state to true (the added page will be used to display Table Of Content). * @access public * @since 1.0 * @see startPage(), endPage(), addTOCPage(), endTOCPage(), getPageSizeFromFormat(), setPageFormat() */ public function AddPage($orientation='', $format='', $keepmargins=false, $tocpage=false) { if ($this->inxobj) { // we are inside an XObject template return; } if (!isset($this->original_lMargin) OR $keepmargins) { $this->original_lMargin = $this->lMargin; } if (!isset($this->original_rMargin) OR $keepmargins) { $this->original_rMargin = $this->rMargin; } // terminate previous page $this->endPage(); // start new page $this->startPage($orientation, $format, $tocpage); } /** * Terminate the current page * @param boolean $tocpage if true set the tocpage state to false (end the page used to display Table Of Content). * @access public * @since 4.2.010 (2008-11-14) * @see AddPage(), startPage(), addTOCPage(), endTOCPage() */ public function endPage($tocpage=false) { // check if page is already closed if (($this->page == 0) OR ($this->numpages > $this->page) OR (!$this->pageopen[$this->page])) { return; } $this->InFooter = true; // print page footer $this->setFooter(); // close page $this->_endpage(); // mark page as closed $this->pageopen[$this->page] = false; $this->InFooter = false; if ($tocpage) { $this->tocpage = false; } } /** * Starts a new page to the document. The page must be closed using the endPage() function. * The origin of the coordinate system is at the top-left corner and increasing ordinates go downwards. * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul> * @param mixed $format The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() or an array of parameters specified at setPageFormat(). * @access public * @since 4.2.010 (2008-11-14) * @see AddPage(), endPage(), addTOCPage(), endTOCPage(), getPageSizeFromFormat(), setPageFormat() */ public function startPage($orientation='', $format='', $tocpage=false) { if ($tocpage) { $this->tocpage = true; } if ($this->numpages > $this->page) { // this page has been already added $this->setPage($this->page + 1); $this->SetY($this->tMargin); return; } // start a new page if ($this->state == 0) { $this->Open(); } ++$this->numpages; $this->swapMargins($this->booklet); // save current graphic settings $gvars = $this->getGraphicVars(); // start new page $this->_beginpage($orientation, $format); // mark page as open $this->pageopen[$this->page] = true; // restore graphic settings $this->setGraphicVars($gvars); // mark this point $this->setPageMark(); // print page header $this->setHeader(); // restore graphic settings $this->setGraphicVars($gvars); // mark this point $this->setPageMark(); // print table header (if any) $this->setTableHeader(); // set mark for empty page check $this->emptypagemrk[$this->page]= $this->pagelen[$this->page]; } /** * Set start-writing mark on current page stream used to put borders and fills. * Borders and fills are always created after content and inserted on the position marked by this method. * This function must be called after calling Image() function for a background image. * Background images must be always inserted before calling Multicell() or WriteHTMLCell() or WriteHTML() functions. * @access public * @since 4.0.016 (2008-07-30) */ public function setPageMark() { $this->intmrk[$this->page] = $this->pagelen[$this->page]; $this->bordermrk[$this->page] = $this->intmrk[$this->page]; $this->setContentMark(); } /** * Set start-writing mark on selected page. * Borders and fills are always created after content and inserted on the position marked by this method. * @param int $page page number (default is the current page) * @access protected * @since 4.6.021 (2009-07-20) */ protected function setContentMark($page=0) { if ($page <= 0) { $page = $this->page; } if (isset($this->footerlen[$page])) { $this->cntmrk[$page] = $this->pagelen[$page] - $this->footerlen[$page]; } else { $this->cntmrk[$page] = $this->pagelen[$page]; } } /** * Set header data. * @param string $ln header image logo * @param string $lw header image logo width in mm * @param string $ht string to print as title on document header * @param string $hs string to print on document header * @access public */ public function setHeaderData($ln='', $lw=0, $ht='', $hs='') { $this->header_logo = $ln; $this->header_logo_width = $lw; $this->header_title = $ht; $this->header_string = $hs; } /** * Returns header data: * <ul><li>$ret['logo'] = logo image</li><li>$ret['logo_width'] = width of the image logo in user units</li><li>$ret['title'] = header title</li><li>$ret['string'] = header description string</li></ul> * @return array() * @access public * @since 4.0.012 (2008-07-24) */ public function getHeaderData() { $ret = array(); $ret['logo'] = $this->header_logo; $ret['logo_width'] = $this->header_logo_width; $ret['title'] = $this->header_title; $ret['string'] = $this->header_string; return $ret; } /** * Set header margin. * (minimum distance between header and top page margin) * @param int $hm distance in user units * @access public */ public function setHeaderMargin($hm=10) { $this->header_margin = $hm; } /** * Returns header margin in user units. * @return float * @since 4.0.012 (2008-07-24) * @access public */ public function getHeaderMargin() { return $this->header_margin; } /** * Set footer margin. * (minimum distance between footer and bottom page margin) * @param int $fm distance in user units * @access public */ public function setFooterMargin($fm=10) { $this->footer_margin = $fm; } /** * Returns footer margin in user units. * @return float * @since 4.0.012 (2008-07-24) * @access public */ public function getFooterMargin() { return $this->footer_margin; } /** * Set a flag to print page header. * @param boolean $val set to true to print the page header (default), false otherwise. * @access public */ public function setPrintHeader($val=true) { $this->print_header = $val; } /** * Set a flag to print page footer. * @param boolean $value set to true to print the page footer (default), false otherwise. * @access public */ public function setPrintFooter($val=true) { $this->print_footer = $val; } /** * Return the right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image * @return float * @access public */ public function getImageRBX() { return $this->img_rb_x; } /** * Return the right-bottom (or left-bottom for RTL) corner Y coordinate of last inserted image * @return float * @access public */ public function getImageRBY() { return $this->img_rb_y; } /** * This method is used to render the page header. * It is automatically called by AddPage() and could be overwritten in your own inherited class. * @access public */ public function Header() { $ormargins = $this->getOriginalMargins(); $headerfont = $this->getHeaderFont(); $headerdata = $this->getHeaderData(); if (($headerdata['logo']) AND ($headerdata['logo'] != K_BLANK_IMAGE)) { $this->Image($headerdata['logo'], '', '', $headerdata['logo_width']); $imgy = $this->getImageRBY(); } else { $imgy = $this->GetY(); } $cell_height = round(($this->getCellHeightRatio() * $headerfont[2]) / $this->getScaleFactor(), 2); // set starting margin for text data cell if ($this->getRTL()) { $header_x = $ormargins['right'] + ($headerdata['logo_width'] * 1.1); } else { $header_x = $ormargins['left'] + ($headerdata['logo_width'] * 1.1); } $this->SetTextColor(0, 0, 0); // header title $this->SetFont($headerfont[0], 'B', $headerfont[2] + 1); $this->SetX($header_x); $this->Cell(0, $cell_height, $headerdata['title'], 0, 1, '', 0, '', 0); // header string $this->SetFont($headerfont[0], $headerfont[1], $headerfont[2]); $this->SetX($header_x); $this->MultiCell(0, $cell_height, $headerdata['string'], 0, '', 0, 1, '', '', true, 0, false); // print an ending header line $this->SetLineStyle(array('width' => 0.85 / $this->getScaleFactor(), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0))); $this->SetY((2.835 / $this->getScaleFactor()) + max($imgy, $this->GetY())); if ($this->getRTL()) { $this->SetX($ormargins['right']); } else { $this->SetX($ormargins['left']); } $this->Cell(0, 0, '', 'T', 0, 'C'); } /** * This method is used to render the page footer. * It is automatically called by AddPage() and could be overwritten in your own inherited class. * @access public */ public function Footer() { $cur_y = $this->GetY(); $ormargins = $this->getOriginalMargins(); $this->SetTextColor(0, 0, 0); //set style for cell border $line_width = 0.85 / $this->getScaleFactor(); $this->SetLineStyle(array('width' => $line_width, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0))); //print document barcode $barcode = $this->getBarcode(); if (!empty($barcode)) { $this->Ln($line_width); $barcode_width = round(($this->getPageWidth() - $ormargins['left'] - $ormargins['right']) / 3); $style = array( 'position' => $this->rtl?'R':'L', 'align' => $this->rtl?'R':'L', 'stretch' => false, 'fitwidth' => true, 'cellfitalign' => '', 'border' => false, 'padding' => 0, 'fgcolor' => array(0,0,0), 'bgcolor' => false, 'text' => false ); $this->write1DBarcode($barcode, 'C128B', '', $cur_y + $line_width, '', (($this->getFooterMargin() / 3) - $line_width), 0.3, $style, ''); } if (empty($this->pagegroups)) { $pagenumtxt = $this->l['w_page'].' '.$this->getAliasNumPage().' / '.$this->getAliasNbPages(); } else { $pagenumtxt = $this->l['w_page'].' '.$this->getPageNumGroupAlias().' / '.$this->getPageGroupAlias(); } $this->SetY($cur_y); //Print page number if ($this->getRTL()) { $this->SetX($ormargins['right']); $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'L'); } else { $this->SetX($ormargins['left']); $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'R'); } } /** * This method is used to render the page header. * @access protected * @since 4.0.012 (2008-07-24) */ protected function setHeader() { if ($this->print_header) { $this->setGraphicVars($this->default_graphic_vars); $temp_thead = $this->thead; $temp_theadMargins = $this->theadMargins; $lasth = $this->lasth; $this->_out('q'); $this->rMargin = $this->original_rMargin; $this->lMargin = $this->original_lMargin; $this->cMargin = 0; //set current position if ($this->rtl) { $this->SetXY($this->original_rMargin, $this->header_margin); } else { $this->SetXY($this->original_lMargin, $this->header_margin); } $this->SetFont($this->header_font[0], $this->header_font[1], $this->header_font[2]); $this->Header(); //restore position if ($this->rtl) { $this->SetXY($this->original_rMargin, $this->tMargin); } else { $this->SetXY($this->original_lMargin, $this->tMargin); } $this->_out('Q'); $this->lasth = $lasth; $this->thead = $temp_thead; $this->theadMargins = $temp_theadMargins; $this->newline = false; } } /** * This method is used to render the page footer. * @access protected * @since 4.0.012 (2008-07-24) */ protected function setFooter() { //Page footer // save current graphic settings $gvars = $this->getGraphicVars(); // mark this point $this->footerpos[$this->page] = $this->pagelen[$this->page]; $this->_out("\n"); if ($this->print_footer) { $this->setGraphicVars($this->default_graphic_vars); $this->current_column = 0; $this->num_columns = 1; $temp_thead = $this->thead; $temp_theadMargins = $this->theadMargins; $lasth = $this->lasth; $this->_out('q'); $this->rMargin = $this->original_rMargin; $this->lMargin = $this->original_lMargin; $this->cMargin = 0; //set current position $footer_y = $this->h - $this->footer_margin; if ($this->rtl) { $this->SetXY($this->original_rMargin, $footer_y); } else { $this->SetXY($this->original_lMargin, $footer_y); } $this->SetFont($this->footer_font[0], $this->footer_font[1], $this->footer_font[2]); $this->Footer(); //restore position if ($this->rtl) { $this->SetXY($this->original_rMargin, $this->tMargin); } else { $this->SetXY($this->original_lMargin, $this->tMargin); } $this->_out('Q'); $this->lasth = $lasth; $this->thead = $temp_thead; $this->theadMargins = $temp_theadMargins; } // restore graphic settings $this->setGraphicVars($gvars); $this->current_column = $gvars['current_column']; $this->num_columns = $gvars['num_columns']; // calculate footer length $this->footerlen[$this->page] = $this->pagelen[$this->page] - $this->footerpos[$this->page] + 1; } /** * This method is used to render the table header on new page (if any). * @access protected * @since 4.5.030 (2009-03-25) */ protected function setTableHeader() { if ($this->num_columns > 1) { // multi column mode return; } if (isset($this->theadMargins['top'])) { // restore the original top-margin $this->tMargin = $this->theadMargins['top']; $this->pagedim[$this->page]['tm'] = $this->tMargin; $this->y = $this->tMargin; } if (!$this->empty_string($this->thead) AND (!$this->inthead)) { // set margins $prev_lMargin = $this->lMargin; $prev_rMargin = $this->rMargin; $prev_cMargin = $this->cMargin; $this->lMargin = $this->theadMargins['lmargin'] + ($this->pagedim[$this->page]['olm'] - $this->pagedim[$this->theadMargins['page']]['olm']); $this->rMargin = $this->theadMargins['rmargin'] + ($this->pagedim[$this->page]['orm'] - $this->pagedim[$this->theadMargins['page']]['orm']); $this->cMargin = $this->theadMargins['cmargin']; if ($this->rtl) { $this->x = $this->w - $this->rMargin; } else { $this->x = $this->lMargin; } // print table header $this->writeHTML($this->thead, false, false, false, false, ''); // set new top margin to skip the table headers if (!isset($this->theadMargins['top'])) { $this->theadMargins['top'] = $this->tMargin; } $this->tMargin = $this->y; $this->pagedim[$this->page]['tm'] = $this->tMargin; $this->lasth = 0; $this->lMargin = $prev_lMargin; $this->rMargin = $prev_rMargin; $this->cMargin = $prev_cMargin; } } /** * Returns the current page number. * @return int page number * @access public * @since 1.0 * @see AliasNbPages(), getAliasNbPages() */ public function PageNo() { return $this->page; } /** * Defines a new spot color. * It can be expressed in RGB components or gray scale. * The method can be called before the first page is created and the value is retained from page to page. * @param int $c Cyan color for CMYK. Value between 0 and 255 * @param int $m Magenta color for CMYK. Value between 0 and 255 * @param int $y Yellow color for CMYK. Value between 0 and 255 * @param int $k Key (Black) color for CMYK. Value between 0 and 255 * @access public * @since 4.0.024 (2008-09-12) * @see SetDrawSpotColor(), SetFillSpotColor(), SetTextSpotColor() */ public function AddSpotColor($name, $c, $m, $y, $k) { if (!isset($this->spot_colors[$name])) { $i = 1 + count($this->spot_colors); $this->spot_colors[$name] = array('i' => $i, 'c' => $c, 'm' => $m, 'y' => $y, 'k' => $k); } } /** * Defines the color used for all drawing operations (lines, rectangles and cell borders). * It can be expressed in RGB components or gray scale. * The method can be called before the first page is created and the value is retained from page to page. * @param array $color array of colors * @param boolean $ret if true do not send the command. * @return string the PDF command * @access public * @since 3.1.000 (2008-06-11) * @see SetDrawColor() */ public function SetDrawColorArray($color, $ret=false) { if (is_array($color)) { $color = array_values($color); $r = isset($color[0]) ? $color[0] : -1; $g = isset($color[1]) ? $color[1] : -1; $b = isset($color[2]) ? $color[2] : -1; $k = isset($color[3]) ? $color[3] : -1; if ($r >= 0) { return $this->SetDrawColor($r, $g, $b, $k, $ret); } } return ''; } /** * Defines the color used for all drawing operations (lines, rectangles and cell borders). It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page. * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255 * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255 * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255 * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255 * @param boolean $ret if true do not send the command. * @return string the PDF command * @access public * @since 1.3 * @see SetDrawColorArray(), SetFillColor(), SetTextColor(), Line(), Rect(), Cell(), MultiCell() */ public function SetDrawColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false) { // set default values if (!is_numeric($col1)) { $col1 = 0; } if (!is_numeric($col2)) { $col2 = -1; } if (!is_numeric($col3)) { $col3 = -1; } if (!is_numeric($col4)) { $col4 = -1; } //Set color for all stroking operations if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) { // Grey scale $this->DrawColor = sprintf('%.3F G', $col1/255); $this->strokecolor = array('G' => $col1); } elseif ($col4 == -1) { // RGB $this->DrawColor = sprintf('%.3F %.3F %.3F RG', $col1/255, $col2/255, $col3/255); $this->strokecolor = array('R' => $col1, 'G' => $col2, 'B' => $col3); } else { // CMYK $this->DrawColor = sprintf('%.3F %.3F %.3F %.3F K', $col1/100, $col2/100, $col3/100, $col4/100); $this->strokecolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4); } if ($this->page > 0) { if (!$ret) { $this->_out($this->DrawColor); } return $this->DrawColor; } return ''; } /** * Defines the spot color used for all drawing operations (lines, rectangles and cell borders). * @param string $name name of the spot color * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default). * @access public * @since 4.0.024 (2008-09-12) * @see AddSpotColor(), SetFillSpotColor(), SetTextSpotColor() */ public function SetDrawSpotColor($name, $tint=100) { if (!isset($this->spot_colors[$name])) { $this->Error('Undefined spot color: '.$name); } $this->DrawColor = sprintf('/CS%d CS %.3F SCN', $this->spot_colors[$name]['i'], $tint/100); if ($this->page > 0) { $this->_out($this->DrawColor); } } /** * Defines the color used for all filling operations (filled rectangles and cell backgrounds). * It can be expressed in RGB components or gray scale. * The method can be called before the first page is created and the value is retained from page to page. * @param array $color array of colors * @access public * @since 3.1.000 (2008-6-11) * @see SetFillColor() */ public function SetFillColorArray($color) { if (is_array($color)) { $color = array_values($color); $r = isset($color[0]) ? $color[0] : -1; $g = isset($color[1]) ? $color[1] : -1; $b = isset($color[2]) ? $color[2] : -1; $k = isset($color[3]) ? $color[3] : -1; if ($r >= 0) { $this->SetFillColor($r, $g, $b, $k); } } } /** * Defines the color used for all filling operations (filled rectangles and cell backgrounds). It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page. * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255 * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255 * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255 * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255 * @access public * @since 1.3 * @see SetFillColorArray(), SetDrawColor(), SetTextColor(), Rect(), Cell(), MultiCell() */ public function SetFillColor($col1=0, $col2=-1, $col3=-1, $col4=-1) { // set default values if (!is_numeric($col1)) { $col1 = 0; } if (!is_numeric($col2)) { $col2 = -1; } if (!is_numeric($col3)) { $col3 = -1; } if (!is_numeric($col4)) { $col4 = -1; } //Set color for all filling operations if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) { // Grey scale $this->FillColor = sprintf('%.3F g', $col1/255); $this->bgcolor = array('G' => $col1); } elseif ($col4 == -1) { // RGB $this->FillColor = sprintf('%.3F %.3F %.3F rg', $col1/255, $col2/255, $col3/255); $this->bgcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3); } else { // CMYK $this->FillColor = sprintf('%.3F %.3F %.3F %.3F k', $col1/100, $col2/100, $col3/100, $col4/100); $this->bgcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4); } $this->ColorFlag = ($this->FillColor != $this->TextColor); if ($this->page > 0) { $this->_out($this->FillColor); } } /** * Defines the spot color used for all filling operations (filled rectangles and cell backgrounds). * @param string $name name of the spot color * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default). * @access public * @since 4.0.024 (2008-09-12) * @see AddSpotColor(), SetDrawSpotColor(), SetTextSpotColor() */ public function SetFillSpotColor($name, $tint=100) { if (!isset($this->spot_colors[$name])) { $this->Error('Undefined spot color: '.$name); } $this->FillColor = sprintf('/CS%d cs %.3F scn', $this->spot_colors[$name]['i'], $tint/100); $this->ColorFlag = ($this->FillColor != $this->TextColor); if ($this->page > 0) { $this->_out($this->FillColor); } } /** * Defines the color used for text. It can be expressed in RGB components or gray scale. * The method can be called before the first page is created and the value is retained from page to page. * @param array $color array of colors * @access public * @since 3.1.000 (2008-6-11) * @see SetFillColor() */ public function SetTextColorArray($color) { if (is_array($color)) { $color = array_values($color); $r = isset($color[0]) ? $color[0] : -1; $g = isset($color[1]) ? $color[1] : -1; $b = isset($color[2]) ? $color[2] : -1; $k = isset($color[3]) ? $color[3] : -1; if ($r >= 0) { $this->SetTextColor($r, $g, $b, $k); } } } /** * Defines the color used for text. It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page. * @param int $col1 Gray level for single color, or Red color for RGB, or Cyan color for CMYK. Value between 0 and 255 * @param int $col2 Green color for RGB, or Magenta color for CMYK. Value between 0 and 255 * @param int $col3 Blue color for RGB, or Yellow color for CMYK. Value between 0 and 255 * @param int $col4 Key (Black) color for CMYK. Value between 0 and 255 * @access public * @since 1.3 * @see SetTextColorArray(), SetDrawColor(), SetFillColor(), Text(), Cell(), MultiCell() */ public function SetTextColor($col1=0, $col2=-1, $col3=-1, $col4=-1) { // set default values if (!is_numeric($col1)) { $col1 = 0; } if (!is_numeric($col2)) { $col2 = -1; } if (!is_numeric($col3)) { $col3 = -1; } if (!is_numeric($col4)) { $col4 = -1; } //Set color for text if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) { // Grey scale $this->TextColor = sprintf('%.3F g', $col1/255); $this->fgcolor = array('G' => $col1); } elseif ($col4 == -1) { // RGB $this->TextColor = sprintf('%.3F %.3F %.3F rg', $col1/255, $col2/255, $col3/255); $this->fgcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3); } else { // CMYK $this->TextColor = sprintf('%.3F %.3F %.3F %.3F k', $col1/100, $col2/100, $col3/100, $col4/100); $this->fgcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4); } $this->ColorFlag = ($this->FillColor != $this->TextColor); } /** * Defines the spot color used for text. * @param string $name name of the spot color * @param int $tint the intensity of the color (from 0 to 100 ; 100 = full intensity by default). * @access public * @since 4.0.024 (2008-09-12) * @see AddSpotColor(), SetDrawSpotColor(), SetFillSpotColor() */ public function SetTextSpotColor($name, $tint=100) { if (!isset($this->spot_colors[$name])) { $this->Error('Undefined spot color: '.$name); } $this->TextColor = sprintf('/CS%d cs %.3F scn', $this->spot_colors[$name]['i'], $tint/100); $this->ColorFlag = ($this->FillColor != $this->TextColor); if ($this->page > 0) { $this->_out($this->TextColor); } } /** * Returns the length of a string in user unit. A font must be selected.<br> * @param string $s The string whose length is to be computed * @param string $fontname Family font. It can be either a name defined by AddFont() or one of the standard families. It is also possible to pass an empty string, in that case, the current family is retained. * @param string $fontstyle Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line-trough</li><li>O: overline</li></ul> or any combination. The default value is regular. * @param float $fontsize Font size in points. The default value is the current size. * @param boolean $getarray if true returns an array of characters widths, if false returns the total length. * @return mixed int total string length or array of characted widths * @author Nicola Asuni * @access public * @since 1.2 */ public function GetStringWidth($s, $fontname='', $fontstyle='', $fontsize=0, $getarray=false) { return $this->GetArrStringWidth($this->utf8Bidi($this->UTF8StringToArray($s), $s, $this->tmprtl), $fontname, $fontstyle, $fontsize, $getarray); } /** * Returns the string length of an array of chars in user unit or an array of characters widths. A font must be selected.<br> * @param string $sa The array of chars whose total length is to be computed * @param string $fontname Family font. It can be either a name defined by AddFont() or one of the standard families. It is also possible to pass an empty string, in that case, the current family is retained. * @param string $fontstyle Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line trough</li><li>O: overline</li></ul> or any combination. The default value is regular. * @param float $fontsize Font size in points. The default value is the current size. * @param boolean $getarray if true returns an array of characters widths, if false returns the total length. * @return mixed int total string length or array of characted widths * @author Nicola Asuni * @access public * @since 2.4.000 (2008-03-06) */ public function GetArrStringWidth($sa, $fontname='', $fontstyle='', $fontsize=0, $getarray=false) { // store current values if (!$this->empty_string($fontname)) { $prev_FontFamily = $this->FontFamily; $prev_FontStyle = $this->FontStyle; $prev_FontSizePt = $this->FontSizePt; $this->SetFont($fontname, $fontstyle, $fontsize); } // convert UTF-8 array to Latin1 if required $sa = $this->UTF8ArrToLatin1($sa); $w = 0; // total width $wa = array(); // array of characters widths foreach ($sa as $char) { // character width $cw = $this->GetCharWidth($char); $wa[] = $cw; $w += $cw; } // restore previous values if (!$this->empty_string($fontname)) { $this->SetFont($prev_FontFamily, $prev_FontStyle, $prev_FontSizePt); } if ($getarray) { return $wa; } return $w; } /** * Returns the length of the char in user unit for the current font. * @param int $char The char code whose length is to be returned * @return int char width * @author Nicola Asuni * @access public * @since 2.4.000 (2008-03-06) */ public function GetCharWidth($char) { if ($char == 173) { // SHY character will not be printed return (0); } $cw = &$this->CurrentFont['cw']; if (isset($cw[$char])) { $w = $cw[$char]; } elseif (isset($this->CurrentFont['dw'])) { // default width $w = $this->CurrentFont['dw']; } elseif (isset($cw[32])) { // default width $w = $cw[32]; } else { $w = 600; } return ($w * $this->FontSize / 1000); } /** * Returns the numbero of characters in a string. * @param string $s The input string. * @return int number of characters * @access public * @since 2.0.0001 (2008-01-07) */ public function GetNumChars($s) { if ($this->isUnicodeFont()) { return count($this->UTF8StringToArray($s)); } return strlen($s); } /** * Fill the list of available fonts ($this->fontlist). * @access protected * @since 4.0.013 (2008-07-28) */ protected function getFontsList() { $fontsdir = opendir($this->_getfontpath()); while (($file = readdir($fontsdir)) !== false) { if (substr($file, -4) == '.php') { array_push($this->fontlist, strtolower(basename($file, '.php'))); } } closedir($fontsdir); } /** * Imports a TrueType, Type1, core, or CID0 font and makes it available. * It is necessary to generate a font definition file first (read /fonts/utils/README.TXT). * The definition file (and the font file itself when embedding) must be present either in the current directory or in the one indicated by K_PATH_FONTS if the constant is defined. If it could not be found, the error "Could not include font definition file" is generated. * @param string $family Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font. * @param string $style Font style. Possible values are (case insensitive):<ul><li>empty string: regular (default)</li><li>B: bold</li><li>I: italic</li><li>BI or IB: bold italic</li></ul> * @param string $fontfile The font definition file. By default, the name is built from the family and style, in lower case with no spaces. * @return array containing the font data, or false in case of error. * @param mixed $subset if true embedd only a subset of the font (stores only the information related to the used characters); if false embedd full font; if 'default' uses the default value set using setFontSubsetting(). This option is valid only for TrueTypeUnicode fonts. If you want to enable users to change the document, set this parameter to false. If you subset the font, the person who receives your PDF would need to have your same font in order to make changes to your PDF. The file size of the PDF would also be smaller because you are embedding only part of a font. * @access public * @since 1.5 * @see SetFont(), setFontSubsetting() */ public function AddFont($family, $style='', $fontfile='', $subset='default') { if ($subset === 'default') { $subset = $this->font_subsetting; } if ($this->empty_string($family)) { if (!$this->empty_string($this->FontFamily)) { $family = $this->FontFamily; } else { $this->Error('Empty font family'); } } // move embedded styles on $style if (substr($family, -1) == 'I') { $style .= 'I'; $family = substr($family, 0, -1); } if (substr($family, -1) == 'B') { $style .= 'B'; $family = substr($family, 0, -1); } // normalize family name $family = strtolower($family); if ((!$this->isunicode) AND ($family == 'arial')) { $family = 'helvetica'; } if (($family == 'symbol') OR ($family == 'zapfdingbats')) { $style = ''; } $tempstyle = strtoupper($style); $style = ''; // underline if (strpos($tempstyle, 'U') !== false) { $this->underline = true; } else { $this->underline = false; } // line-through (deleted) if (strpos($tempstyle, 'D') !== false) { $this->linethrough = true; } else { $this->linethrough = false; } // overline if (strpos($tempstyle, 'O') !== false) { $this->overline = true; } else { $this->overline = false; } // bold if (strpos($tempstyle, 'B') !== false) { $style .= 'B'; } // oblique if (strpos($tempstyle, 'I') !== false) { $style .= 'I'; } $bistyle = $style; $fontkey = $family.$style; $font_style = $style.($this->underline ? 'U' : '').($this->linethrough ? 'D' : '').($this->overline ? 'O' : ''); $fontdata = array('fontkey' => $fontkey, 'family' => $family, 'style' => $font_style); // check if the font has been already added $fb = $this->getFontBuffer($fontkey); if ($fb !== false) { if ($this->inxobj) { // we are inside an XObject template $this->xobjects[$this->xobjid]['fonts'][$fontkey] = $fb['i']; } return $fontdata; } if (isset($type)) { unset($type); } if (isset($cw)) { unset($cw); } // get specified font directory (if any) $fontdir = false; if (!$this->empty_string($fontfile)) { $fontdir = dirname($fontfile); if ($this->empty_string($fontdir) OR ($fontdir == '.')) { $fontdir = ''; } else { $fontdir .= '/'; } } // search and include font file if ($this->empty_string($fontfile) OR (!file_exists($fontfile))) { // build a standard filenames for specified font $fontfile1 = str_replace(' ', '', $family).strtolower($style).'.php'; $fontfile2 = str_replace(' ', '', $family).'.php'; // search files on various directories if (($fontdir !== false) AND file_exists($fontdir.$fontfile1)) { $fontfile = $fontdir.$fontfile1; } elseif (file_exists($this->_getfontpath().$fontfile1)) { $fontfile = $this->_getfontpath().$fontfile1; } elseif (file_exists($fontfile1)) { $fontfile = $fontfile1; } elseif (($fontdir !== false) AND file_exists($fontdir.$fontfile2)) { $fontfile = $fontdir.$fontfile2; } elseif (file_exists($this->_getfontpath().$fontfile2)) { $fontfile = $this->_getfontpath().$fontfile2; } else { $fontfile = $fontfile2; } } // include font file if (file_exists($fontfile)) { include($fontfile); } else { $this->Error('Could not include font definition file: '.$family.''); } // check font parameters if ((!isset($type)) OR (!isset($cw))) { $this->Error('The font definition file has a bad format: '.$fontfile.''); } // SET default parameters if (!isset($file) OR $this->empty_string($file)) { $file = ''; } if (!isset($enc) OR $this->empty_string($enc)) { $enc = ''; } if (!isset($cidinfo) OR $this->empty_string($cidinfo)) { $cidinfo = array('Registry'=>'Adobe','Ordering'=>'Identity','Supplement'=>0); $cidinfo['uni2cid'] = array(); } if (!isset($ctg) OR $this->empty_string($ctg)) { $ctg = ''; } if (!isset($desc) OR $this->empty_string($desc)) { $desc = array(); } if (!isset($up) OR $this->empty_string($up)) { $up = -100; } if (!isset($ut) OR $this->empty_string($ut)) { $ut = 50; } if (!isset($cw) OR $this->empty_string($cw)) { $cw = array(); } if (!isset($dw) OR $this->empty_string($dw)) { // set default width if (isset($desc['MissingWidth']) AND ($desc['MissingWidth'] > 0)) { $dw = $desc['MissingWidth']; } elseif (isset($cw[32])) { $dw = $cw[32]; } else { $dw = 600; } } ++$this->numfonts; if ($type == 'cidfont0') { // register CID font (all styles at once) $styles = array('' => '', 'B' => ',Bold', 'I' => ',Italic', 'BI' => ',BoldItalic'); $sname = $name.$styles[$bistyle]; // artificial bold if (strpos($bistyle, 'B') !== false) { if (isset($desc['StemV'])) { $desc['StemV'] *= 2; } else { $desc['StemV'] = 120; } } // artificial italic if (strpos($bistyle, 'I') !== false) { if (isset($desc['ItalicAngle'])) { $desc['ItalicAngle'] -= 11; } else { $desc['ItalicAngle'] = -11; } } } elseif ($type == 'core') { $name = $this->CoreFonts[$fontkey]; $subset = false; } elseif (($type == 'TrueType') OR ($type == 'Type1')) { $subset = false; } elseif ($type == 'TrueTypeUnicode') { $enc = 'Identity-H'; } else { $this->Error('Unknow font type: '.$type.''); } // initialize subsetchars to contain default ASCII values (0-255) $subsetchars = array_fill(0, 256, true); $this->setFontBuffer($fontkey, array('fontkey' => $fontkey, 'i' => $this->numfonts, 'type' => $type, 'name' => $name, 'desc' => $desc, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'dw' => $dw, 'enc' => $enc, 'cidinfo' => $cidinfo, 'file' => $file, 'ctg' => $ctg, 'subset' => $subset, 'subsetchars' => $subsetchars)); if ($this->inxobj) { // we are inside an XObject template $this->xobjects[$this->xobjid]['fonts'][$fontkey] = $this->numfonts; } if (isset($diff) AND (!empty($diff))) { //Search existing encodings $d = 0; $nb = count($this->diffs); for ($i=1; $i <= $nb; ++$i) { if ($this->diffs[$i] == $diff) { $d = $i; break; } } if ($d == 0) { $d = $nb + 1; $this->diffs[$d] = $diff; } $this->setFontSubBuffer($fontkey, 'diff', $d); } if (!$this->empty_string($file)) { if (!isset($this->FontFiles[$file])) { if ((strcasecmp($type,'TrueType') == 0) OR (strcasecmp($type, 'TrueTypeUnicode') == 0)) { $this->FontFiles[$file] = array('length1' => $originalsize, 'fontdir' => $fontdir, 'subset' => $subset, 'fontkeys' => array($fontkey)); } elseif ($type != 'core') { $this->FontFiles[$file] = array('length1' => $size1, 'length2' => $size2, 'fontdir' => $fontdir, 'subset' => $subset, 'fontkeys' => array($fontkey)); } } else { // update fontkeys that are sharing this font file $this->FontFiles[$file]['subset'] = ($this->FontFiles[$file]['subset'] AND $subset); if (!in_array($fontkey, $this->FontFiles[$file]['fontkeys'])) { $this->FontFiles[$file]['fontkeys'][] = $fontkey; } } } return $fontdata; } /** * Sets the font used to print character strings. * The font can be either a standard one or a font added via the AddFont() method. Standard fonts use Windows encoding cp1252 (Western Europe). * The method can be called before the first page is created and the font is retained from page to page. * If you just wish to change the current font size, it is simpler to call SetFontSize(). * Note: for the standard fonts, the font metric files must be accessible. There are three possibilities for this:<ul><li>They are in the current directory (the one where the running script lies)</li><li>They are in one of the directories defined by the include_path parameter</li><li>They are in the directory defined by the K_PATH_FONTS constant</li></ul><br /> * @param string $family Family font. It can be either a name defined by AddFont() or one of the standard Type1 families (case insensitive):<ul><li>times (Times-Roman)</li><li>timesb (Times-Bold)</li><li>timesi (Times-Italic)</li><li>timesbi (Times-BoldItalic)</li><li>helvetica (Helvetica)</li><li>helveticab (Helvetica-Bold)</li><li>helveticai (Helvetica-Oblique)</li><li>helveticabi (Helvetica-BoldOblique)</li><li>courier (Courier)</li><li>courierb (Courier-Bold)</li><li>courieri (Courier-Oblique)</li><li>courierbi (Courier-BoldOblique)</li><li>symbol (Symbol)</li><li>zapfdingbats (ZapfDingbats)</li></ul> It is also possible to pass an empty string. In that case, the current family is retained. * @param string $style Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line trough</li><li>O: overline</li></ul> or any combination. The default value is regular. Bold and italic styles do not apply to Symbol and ZapfDingbats basic fonts or other fonts when not defined. * @param float $size Font size in points. The default value is the current size. If no size has been specified since the beginning of the document, the value taken is 12 * @param string $fontfile The font definition file. By default, the name is built from the family and style, in lower case with no spaces. * @param mixed $subset if true embedd only a subset of the font (stores only the information related to the used characters); if false embedd full font; if 'default' uses the default value set using setFontSubsetting(). This option is valid only for TrueTypeUnicode fonts. If you want to enable users to change the document, set this parameter to false. If you subset the font, the person who receives your PDF would need to have your same font in order to make changes to your PDF. The file size of the PDF would also be smaller because you are embedding only part of a font. * @author Nicola Asuni * @access public * @since 1.0 * @see AddFont(), SetFontSize() */ public function SetFont($family, $style='', $size=0, $fontfile='', $subset='default') { //Select a font; size given in points if ($size == 0) { $size = $this->FontSizePt; } // try to add font (if not already added) $fontdata = $this->AddFont($family, $style, $fontfile, $subset); $this->FontFamily = $fontdata['family']; $this->FontStyle = $fontdata['style']; $this->CurrentFont = $this->getFontBuffer($fontdata['fontkey']); $this->SetFontSize($size); } /** * Defines the size of the current font. * @param float $size The size (in points) * @param boolean $out if true output the font size command, otherwise only set the font properties. * @access public * @since 1.0 * @see SetFont() */ public function SetFontSize($size, $out=true) { //Set font size in points $this->FontSizePt = $size; $this->FontSize = $size / $this->k; if (isset($this->CurrentFont['desc']['Ascent']) AND ($this->CurrentFont['desc']['Ascent'] > 0)) { $this->FontAscent = $this->CurrentFont['desc']['Ascent'] * $this->FontSize / 1000; } else { $this->FontAscent = 0.85 * $this->FontSize; } if (isset($this->CurrentFont['desc']['Descent']) AND ($this->CurrentFont['desc']['Descent'] <= 0)) { $this->FontDescent = - $this->CurrentFont['desc']['Descent'] * $this->FontSize / 1000; } else { $this->FontDescent = 0.15 * $this->FontSize; } if ($out AND ($this->page > 0) AND (isset($this->CurrentFont['i']))) { $this->_out(sprintf('BT /F%d %.2F Tf ET', $this->CurrentFont['i'], $this->FontSizePt)); } } /** * Return the font descent value * @param string $font font name * @param string $style font style * @param float $size The size (in points) * @return int font descent * @access public * @author Nicola Asuni * @since 4.9.003 (2010-03-30) */ public function getFontDescent($font, $style='', $size=0) { //Set font size in points $sizek = $size / $this->k; $fontdata = $this->AddFont($font, $style); $fontinfo = $this->getFontBuffer($fontdata['fontkey']); if (isset($fontinfo['desc']['Descent']) AND ($fontinfo['desc']['Descent'] <= 0)) { $descent = - $fontinfo['desc']['Descent'] * $sizek / 1000; } else { $descent = 0.15 * $sizek; } return $descent; } /** * Return the font ascent value * @param string $font font name * @param string $style font style * @param float $size The size (in points) * @return int font ascent * @access public * @author Nicola Asuni * @since 4.9.003 (2010-03-30) */ public function getFontAscent($font, $style='', $size=0) { //Set font size in points $sizek = $size / $this->k; $fontdata = $this->AddFont($font, $style); $fontinfo = $this->getFontBuffer($fontdata['fontkey']); if (isset($fontinfo['desc']['Ascent']) AND ($fontinfo['desc']['Ascent'] > 0)) { $ascent = $fontinfo['desc']['Ascent'] * $sizek / 1000; } else { $ascent = 0.85 * $sizek; } return $ascent; } /** * Defines the default monospaced font. * @param string $font Font name. * @access public * @since 4.5.025 */ public function SetDefaultMonospacedFont($font) { $this->default_monospaced_font = $font; } /** * Creates a new internal link and returns its identifier. An internal link is a clickable area which directs to another place within the document.<br /> * The identifier can then be passed to Cell(), Write(), Image() or Link(). The destination is defined with SetLink(). * @access public * @since 1.5 * @see Cell(), Write(), Image(), Link(), SetLink() */ public function AddLink() { //Create a new internal link $n = count($this->links) + 1; $this->links[$n] = array(0, 0); return $n; } /** * Defines the page and position a link points to. * @param int $link The link identifier returned by AddLink() * @param float $y Ordinate of target position; -1 indicates the current position. The default value is 0 (top of page) * @param int $page Number of target page; -1 indicates the current page. This is the default value * @access public * @since 1.5 * @see AddLink() */ public function SetLink($link, $y=0, $page=-1) { if ($y == -1) { $y = $this->y; } if ($page == -1) { $page = $this->page; } $this->links[$link] = array($page, $y); } /** * Puts a link on a rectangular area of the page. * Text or image links are generally put via Cell(), Write() or Image(), but this method can be useful for instance to define a clickable area inside an image. * @param float $x Abscissa of the upper-left corner of the rectangle * @param float $y Ordinate of the upper-left corner of the rectangle * @param float $w Width of the rectangle * @param float $h Height of the rectangle * @param mixed $link URL or identifier returned by AddLink() * @param int $spaces number of spaces on the text to link * @access public * @since 1.5 * @see AddLink(), Annotation(), Cell(), Write(), Image() */ public function Link($x, $y, $w, $h, $link, $spaces=0) { $this->Annotation($x, $y, $w, $h, $link, array('Subtype'=>'Link'), $spaces); } /** * Puts a markup annotation on a rectangular area of the page. * !!!!THE ANNOTATION SUPPORT IS NOT YET FULLY IMPLEMENTED !!!! * @param float $x Abscissa of the upper-left corner of the rectangle * @param float $y Ordinate of the upper-left corner of the rectangle * @param float $w Width of the rectangle * @param float $h Height of the rectangle * @param string $text annotation text or alternate content * @param array $opt array of options (see section 8.4 of PDF reference 1.7). * @param int $spaces number of spaces on the text to link * @access public * @since 4.0.018 (2008-08-06) */ public function Annotation($x, $y, $w, $h, $text, $opt=array('Subtype'=>'Text'), $spaces=0) { if ($this->inxobj) { // store parameters for later use on template $this->xobjects[$this->xobjid]['annotations'][] = array('x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'text' => $text, 'opt' => $opt, 'spaces' => $spaces); return; } if ($x === '') { $x = $this->x; } if ($y === '') { $y = $this->y; } // recalculate coordinates to account for graphic transformations if (isset($this->transfmatrix) AND !empty($this->transfmatrix)) { for ($i=$this->transfmatrix_key; $i > 0; --$i) { $maxid = count($this->transfmatrix[$i]) - 1; for ($j=$maxid; $j >= 0; --$j) { $ctm = $this->transfmatrix[$i][$j]; if (isset($ctm['a'])) { $x = $x * $this->k; $y = ($this->h - $y) * $this->k; $w = $w * $this->k; $h = $h * $this->k; // top left $xt = $x; $yt = $y; $x1 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e']; $y1 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f']; // top right $xt = $x + $w; $yt = $y; $x2 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e']; $y2 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f']; // bottom left $xt = $x; $yt = $y - $h; $x3 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e']; $y3 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f']; // bottom right $xt = $x + $w; $yt = $y - $h; $x4 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e']; $y4 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f']; // new coordinates (rectangle area) $x = min($x1, $x2, $x3, $x4); $y = max($y1, $y2, $y3, $y4); $w = (max($x1, $x2, $x3, $x4) - $x) / $this->k; $h = ($y - min($y1, $y2, $y3, $y4)) / $this->k; $x = $x / $this->k; $y = $this->h - ($y / $this->k); } } } } if ($this->page <= 0) { $page = 1; } else { $page = $this->page; } if (!isset($this->PageAnnots[$page])) { $this->PageAnnots[$page] = array(); } ++$this->n; $this->PageAnnots[$page][] = array('n' => $this->n, 'x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'txt' => $text, 'opt' => $opt, 'numspaces' => $spaces); if ((($opt['Subtype'] == 'FileAttachment') OR ($opt['Subtype'] == 'Sound')) AND (!$this->empty_string($opt['FS'])) AND file_exists($opt['FS']) AND (!isset($this->embeddedfiles[basename($opt['FS'])]))) { ++$this->n; $this->embeddedfiles[basename($opt['FS'])] = array('n' => $this->n, 'file' => $opt['FS']); } // Add widgets annotation's icons if (isset($opt['mk']['i']) AND file_exists($opt['mk']['i'])) { $this->Image($opt['mk']['i'], '', '', 10, 10, '', '', '', false, 300, '', false, false, 0, false, true); } if (isset($opt['mk']['ri']) AND file_exists($opt['mk']['ri'])) { $this->Image($opt['mk']['ri'], '', '', 0, 0, '', '', '', false, 300, '', false, false, 0, false, true); } if (isset($opt['mk']['ix']) AND file_exists($opt['mk']['ix'])) { $this->Image($opt['mk']['ix'], '', '', 0, 0, '', '', '', false, 300, '', false, false, 0, false, true); } } /** * Embedd the attached files. * @since 4.4.000 (2008-12-07) * @access protected * @see Annotation() */ protected function _putEmbeddedFiles() { reset($this->embeddedfiles); foreach ($this->embeddedfiles as $filename => $filedata) { $data = file_get_contents($filedata['file']); $filter = ''; if ($this->compress) { $data = gzcompress($data); $filter = ' /Filter /FlateDecode'; } $stream = $this->_getrawstream($data, $filedata['n']); $out = $this->_getobj($filedata['n'])."\n"; $out .= '<< /Type /EmbeddedFile'.$filter.' /Length '.strlen($stream).' >>'; $out .= ' stream'."\n".$stream."\n".'endstream'; $out .= "\n".'endobj'; $this->_out($out); } } /** * Prints a text cell at the specified position. * The origin is on the left of the first charcter, on the baseline. * This method allows to place a string precisely on the page. * @param float $x Abscissa of the cell origin * @param float $y Ordinate of the cell origin * @param string $txt String to print * @param int $fstroke outline size in user units (false = disable) * @param boolean $fclip if true activate clipping mode (you must call StartTransform() before this function and StopTransform() to stop the clipping tranformation). * @param boolean $ffill if true fills the text * @param mixed $border Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0))) * @param int $ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL languages)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0. * @param string $align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul> * @param boolean $fill Indicates if the cell background must be painted (true) or transparent (false). * @param mixed $link URL or identifier returned by AddLink(). * @param int $stretch stretch carachter mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if necessary</li><li>2 = forced horizontal scaling</li><li>3 = character spacing only if necessary</li><li>4 = forced character spacing</li></ul> * @param boolean $ignore_min_height if true ignore automatic minimum height value. * @param string $calign cell vertical alignment relative to the specified Y value. Possible values are:<ul><li>T : cell top</li><li>A : font top</li><li>L : font baseline</li><li>D : font bottom</li><li>B : cell bottom</li></ul> * @param string $valign text vertical alignment inside the cell. Possible values are:<ul><li>T : top</li><li>C : center</li><li>B : bottom</li></ul> * @param boolean $rtloff if true uses the page top-left corner as origin of axis for $x and $y initial position. * @access public * @since 1.0 * @see Cell(), Write(), MultiCell(), WriteHTML(), WriteHTMLCell() */ public function Text($x, $y, $txt, $fstroke=false, $fclip=false, $ffill=true, $border=0, $ln=0, $align='', $fill=false, $link='', $stretch=0, $ignore_min_height=false, $calign='T', $valign='M', $rtloff=false) { $textrendermode = $this->textrendermode; $textstrokewidth = $this->textstrokewidth; $this->setTextRenderingMode($fstroke, $ffill, $fclip); $this->SetXY($x, $y, $rtloff); $this->Cell(0, 0, $txt, $border, $ln, $align, $fill, $link, $stretch, $ignore_min_height, $calign, $valign); // restore previous rendering mode $this->textrendermode = $textrendermode; $this->textstrokewidth = $textstrokewidth; } /** * Whenever a page break condition is met, the method is called, and the break is issued or not depending on the returned value. * The default implementation returns a value according to the mode selected by SetAutoPageBreak().<br /> * This method is called automatically and should not be called directly by the application. * @return boolean * @access public * @since 1.4 * @see SetAutoPageBreak() */ public function AcceptPageBreak() { if ($this->num_columns > 1) { // multi column mode if($this->current_column < ($this->num_columns - 1)) { // go to next column $this->selectColumn($this->current_column + 1); } else { // add a new page $this->AddPage(); // set first column $this->selectColumn(0); } // avoid page breaking from checkPageBreak() return false; } return $this->AutoPageBreak; } /** * Add page if needed. * @param float $h Cell height. Default value: 0. * @param mixed $y starting y position, leave empty for current position. * @param boolean $addpage if true add a page, otherwise only return the true/false state * @return boolean true in case of page break, false otherwise. * @since 3.2.000 (2008-07-01) * @access protected */ protected function checkPageBreak($h=0, $y='', $addpage=true) { if ($this->empty_string($y)) { $y = $this->y; } $current_page = $this->page; if ((($y + $h) > $this->PageBreakTrigger) AND (!$this->InFooter) AND ($this->AcceptPageBreak())) { if ($addpage) { //Automatic page break $x = $this->x; $this->AddPage($this->CurOrientation); $this->y = $this->tMargin; $oldpage = $this->page - 1; if ($this->rtl) { if ($this->pagedim[$this->page]['orm'] != $this->pagedim[$oldpage]['orm']) { $this->x = $x - ($this->pagedim[$this->page]['orm'] - $this->pagedim[$oldpage]['orm']); } else { $this->x = $x; } } else { if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) { $this->x = $x + ($this->pagedim[$this->page]['olm'] - $this->pagedim[$oldpage]['olm']); } else { $this->x = $x; } } } $this->newline = true; return true; } if ($current_page != $this->page) { // account for columns mode $this->newline = true; return true; } return false; } /** * Removes SHY characters from text. * Unicode Data:<ul> * <li>Name : SOFT HYPHEN, commonly abbreviated as SHY</li> * <li>HTML Entity (decimal): &amp;#173;</li> * <li>HTML Entity (hex): &amp;#xad;</li> * <li>HTML Entity (named): &amp;shy;</li> * <li>How to type in Microsoft Windows: [Alt +00AD] or [Alt 0173]</li> * <li>UTF-8 (hex): 0xC2 0xAD (c2ad)</li> * <li>UTF-8 character: chr(194).chr(173)</li> * </ul> * @param string $txt input string * @return string without SHY characters. * @access public * @since (4.5.019) 2009-02-28 */ public function removeSHY($txt='') { $txt = preg_replace('/([\\xc2]{1}[\\xad]{1})/', '', $txt); if (!$this->isunicode) { $txt = preg_replace('/([\\xad]{1})/', '', $txt); } return $txt; } /** * Prints a cell (rectangular area) with optional borders, background color and character string. The upper-left corner of the cell corresponds to the current position. The text can be aligned or centered. After the call, the current position moves to the right or to the next line. It is possible to put a link on the text.<br /> * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting. * @param float $w Cell width. If 0, the cell extends up to the right margin. * @param float $h Cell height. Default value: 0. * @param string $txt String to print. Default value: empty string. * @param mixed $border Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0))) * @param int $ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL languages)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul> Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0. * @param string $align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul> * @param boolean $fill Indicates if the cell background must be painted (true) or transparent (false). * @param mixed $link URL or identifier returned by AddLink(). * @param int $stretch stretch carachter mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if necessary</li><li>2 = forced horizontal scaling</li><li>3 = character spacing only if necessary</li><li>4 = forced character spacing</li></ul> * @param boolean $ignore_min_height if true ignore automatic minimum height value. * @param string $calign cell vertical alignment relative to the specified Y value. Possible values are:<ul><li>T : cell top</li><li>C : center</li><li>B : cell bottom</li><li>A : font top</li><li>L : font baseline</li><li>D : font bottom</li></ul> * @param string $valign text vertical alignment inside the cell. Possible values are:<ul><li>T : top</li><li>C : center</li><li>B : bottom</li></ul> * @access public * @since 1.0 * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), AddLink(), Ln(), MultiCell(), Write(), SetAutoPageBreak() */ public function Cell($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='', $stretch=0, $ignore_min_height=false, $calign='T', $valign='M') { if (!$ignore_min_height) { $min_cell_height = $this->FontSize * $this->cell_height_ratio; if ($h < $min_cell_height) { $h = $min_cell_height; } } $this->checkPageBreak($h); $this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch, $ignore_min_height, $calign, $valign)); } /** * Returns the PDF string code to print a cell (rectangular area) with optional borders, background color and character string. The upper-left corner of the cell corresponds to the current position. The text can be aligned or centered. After the call, the current position moves to the right or to the next line. It is possible to put a link on the text.<br /> * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting. * @param float $w Cell width. If 0, the cell extends up to the right margin. * @param float $h Cell height. Default value: 0. * @param string $txt String to print. Default value: empty string. * @param mixed $border Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0))) * @param int $ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL languages)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0. * @param string $align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul> * @param boolean $fill Indicates if the cell background must be painted (true) or transparent (false). * @param mixed $link URL or identifier returned by AddLink(). * @param int $stretch stretch carachter mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if necessary</li><li>2 = forced horizontal scaling</li><li>3 = character spacing only if necessary</li><li>4 = forced character spacing</li></ul> * @param boolean $ignore_min_height if true ignore automatic minimum height value. * @param string $calign cell vertical alignment relative to the specified Y value. Possible values are:<ul><li>T : cell top</li><li>C : center</li><li>B : cell bottom</li><li>A : font top</li><li>L : font baseline</li><li>D : font bottom</li></ul> * @param string $valign text vertical alignment inside the cell. Possible values are:<ul><li>T : top</li><li>M : middle</li><li>B : bottom</li></ul> * @return string containing cell code * @access protected * @since 1.0 * @see Cell() */ protected function getCellCode($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='', $stretch=0, $ignore_min_height=false, $calign='T', $valign='M') { $txt = $this->removeSHY($txt); $rs = ''; //string to be returned if (!$ignore_min_height) { $min_cell_height = $this->FontSize * $this->cell_height_ratio; if ($h < $min_cell_height) { $h = $min_cell_height; } } $k = $this->k; $x = $this->x; $y = $this->y; // cell vertical alignment switch ($calign) { case 'A': { // font top switch ($valign) { case 'T': { // top $y -= ($this->LineWidth / 2); break; } case 'B': { // bottom $y -= ($h - $this->FontAscent - $this->FontDescent - $this->cMargin - ($this->LineWidth / 2)); break; } default: case 'C': case 'M': { // center $y -= (($h - $this->FontAscent - $this->FontDescent) / 2); break; } } break; } case 'L': { // font baseline switch ($valign) { case 'T': { // top $y -= ($this->FontAscent + ($this->LineWidth / 2)); break; } case 'B': { // bottom $y -= ($h - $this->FontDescent- $this->cMargin - ($this->LineWidth / 2)); break; } default: case 'C': case 'M': { // center $y -= (($h + $this->FontAscent - $this->FontDescent) / 2); break; } } break; } case 'D': { // font bottom switch ($valign) { case 'T': { // top $y -= ($this->FontAscent + $this->FontDescent + $this->cMargin + ($this->LineWidth / 2)); break; } case 'B': { // bottom $y -= ($h - ($this->LineWidth / 2)); break; } default: case 'C': case 'M': { // center $y -= (($h + $this->FontAscent + $this->FontDescent) / 2) + $this->cMargin; break; } } break; } case 'B': { // cell bottom $y -= $h; break; } case 'C': { // cell center $y -= ($h / 2); break; } default: case 'T': { // cell top break; } } // text vertical alignment switch ($valign) { case 'T': { // top $basefonty = $y + $this->FontAscent + ($this->LineWidth / 2); $yt = $y + ($this->LineWidth / 2); break; } case 'B': { // bottom $basefonty = $y + $h - $this->FontDescent - $this->cMargin - ($this->LineWidth / 2); $yt = $y + $h - $this->FontSize - $this->cMargin - ($this->LineWidth / 2); break; } default: case 'C': case 'M': { // center $basefonty = $y + (($h + $this->FontAscent - $this->FontDescent) / 2); $yt = $y + (($h - $this->FontSize) / 2); break; } } if ($this->empty_string($w) OR ($w <= 0)) { if ($this->rtl) { $w = $x - $this->lMargin; } else { $w = $this->w - $this->rMargin - $x; } } $s = ''; // fill and borders if (is_string($border) AND (strlen($border) == 4)) { // full border $border = 1; } if ($fill OR ($border == 1)) { if ($fill) { $op = ($border == 1) ? 'B' : 'f'; } else { $op = 'S'; } if ($this->rtl) { $xk = (($this->x - $w) * $k); } else { $xk = ($this->x * $k); } $s .= sprintf('%.2F %.2F %.2F %.2F re %s ', $xk, (($this->h - $y) * $k), ($w * $k), (-$h * $k), $op); } // draw borders $s .= $this->getCellBorder($x, $y, $w, $h, $border); if ($txt != '') { $txt2 = $txt; if ($this->isunicode) { if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) { $txt2 = $this->UTF8ToLatin1($txt2); } else { $unicode = $this->UTF8StringToArray($txt); // array of UTF-8 unicode values $unicode = $this->utf8Bidi($unicode, '', $this->tmprtl); if (defined('K_THAI_TOPCHARS') AND (K_THAI_TOPCHARS == true)) { // ---- Fix for bug #2977340 "Incorrect Thai characters position arrangement" ---- // NOTE: this doesn't work with HTML justification // Symbols that could overlap on the font top (only works in LTR) $topchar = array(3611, 3613, 3615, 3650, 3651, 3652); // chars that extends on top $topsym = array(3633, 3636, 3637, 3638, 3639, 3655, 3656, 3657, 3658, 3659, 3660, 3661, 3662); // symbols with top position $numchars = count($unicode); // number of chars $unik = 0; $uniblock = array(); $uniblock[$unik] = array(); $uniblock[$unik][] = $unicode[0]; // resolve overlapping conflicts by splitting the string in several parts for ($i = 1; $i < $numchars; ++$i) { // check if symbols overlaps at top if (in_array($unicode[$i], $topsym) AND (in_array($unicode[($i - 1)], $topsym) OR in_array($unicode[($i - 1)], $topchar))) { // move symbols to another array ++$unik; $uniblock[$unik] = array(); $uniblock[$unik][] = $unicode[$i]; ++$unik; $uniblock[$unik] = array(); $unicode[$i] = 0x200b; // Unicode Character 'ZERO WIDTH SPACE' (DEC:8203, U+200B) } else { $uniblock[$unik][] = $unicode[$i]; } } // ---- END OF Fix for bug #2977340 } $txt2 = $this->arrUTF8ToUTF16BE($unicode, false); } } $txt2 = $this->_escape($txt2); // text length $txwidth = $this->GetStringWidth($txt); $width = $txwidth; // ratio between cell length and text length if ($width <= 0) { $ratio = 1; } else { $ratio = ($w - (2 * $this->cMargin)) / $width; } // stretch text if required if (($stretch > 0) AND (($ratio < 1) OR (($ratio > 1) AND (($stretch % 2) == 0)))) { if ($stretch > 2) { // spacing //Calculate character spacing in points $char_space = (($w - $width - (2 * $this->cMargin)) * $this->k) / max($this->GetNumChars($txt)-1,1); //Set character spacing $rs .= sprintf('BT %.2F Tc ET ', $char_space); } else { // scaling //Calculate horizontal scaling $horiz_scale = $ratio * 100.0; //Set horizontal scaling $rs .= sprintf('BT %.2F Tz ET ', $horiz_scale); } $align = ''; $width = $w - (2 * $this->cMargin); } else { $stretch == 0; } if ($this->ColorFlag) { $s .= 'q '.$this->TextColor.' '; } // rendering mode $s .= sprintf('BT %d Tr %.2F w ET ', $this->textrendermode, $this->textstrokewidth); // count number of spaces $ns = substr_count($txt, ' '); // Justification $spacewidth = 0; if (($align == 'J') AND ($ns > 0)) { if ($this->isUnicodeFont()) { // get string width without spaces $width = $this->GetStringWidth(str_replace(' ', '', $txt)); // calculate average space width $spacewidth = -1000 * ($w - $width - (2 * $this->cMargin)) / ($ns?$ns:1) / $this->FontSize; // set word position to be used with TJ operator $txt2 = str_replace(chr(0).chr(32), ') '.sprintf('%.3F', $spacewidth).' (', $txt2); $unicode_justification = true; } else { // get string width $width = $txwidth; $spacewidth = (($w - $width - (2 * $this->cMargin)) / ($ns?$ns:1)) * $this->k; // set word spacing $rs .= sprintf('BT %.3F Tw ET ', $spacewidth); } $width = $w - (2 * $this->cMargin); } // replace carriage return characters $txt2 = str_replace("\r", ' ', $txt2); switch ($align) { case 'C': { $dx = ($w - $width) / 2; break; } case 'R': { if ($this->rtl) { $dx = $this->cMargin; } else { $dx = $w - $width - $this->cMargin; } break; } case 'L': { if ($this->rtl) { $dx = $w - $width - $this->cMargin; } else { $dx = $this->cMargin; } break; } case 'J': default: { $dx = $this->cMargin; break; } } if ($this->rtl) { $xdx = $this->x - $dx - $width; } else { $xdx = $this->x + $dx; } $xdk = $xdx * $k; // print text $s .= sprintf('BT %.2F %.2F Td [(%s)] TJ ET', $xdk, (($this->h - $basefonty) * $k), $txt2); if (isset($uniblock)) { // print overlapping characters as separate string $xshift = 0; // horizontal shift $ty = (($this->h - $basefonty + (0.2 * $this->FontSize)) * $k); $spw = (($w - $txwidth - (2 * $this->cMargin)) / ($ns?$ns:1)); foreach ($uniblock as $uk => $uniarr) { if (($uk % 2) == 0) { // x space to skip if ($spacewidth != 0) { // justification shift $xshift += (count(array_keys($uniarr, 32)) * $spw); } $xshift += $this->GetArrStringWidth($uniarr); // + shift justification } else { // character to print $topchr = $this->arrUTF8ToUTF16BE($uniarr, false); $topchr = $this->_escape($topchr); $s .= sprintf(' BT %.2F %.2F Td [(%s)] TJ ET', ($xdk + ($xshift * $k)), $ty, $topchr); } } } if ($this->underline) { $s .= ' '.$this->_dounderlinew($xdx, $basefonty, $width); } if ($this->linethrough) { $s .= ' '.$this->_dolinethroughw($xdx, $basefonty, $width); } if ($this->overline) { $s .= ' '.$this->_dooverlinew($xdx, $basefonty, $width); } if ($this->ColorFlag) { $s .= ' Q'; } if ($link) { $this->Link($xdx, $yt, $width, ($this->FontSize + $this->cMargin), $link, $ns); } } // output cell if ($s) { // output cell $rs .= $s; // reset text stretching if ($stretch > 2) { //Reset character horizontal spacing $rs .= ' BT 0 Tc ET'; } elseif ($stretch > 0) { //Reset character horizontal scaling $rs .= ' BT 100 Tz ET'; } } // reset word spacing if (!$this->isUnicodeFont() AND ($align == 'J')) { $rs .= ' BT 0 Tw ET'; } $this->lasth = $h; if ($ln > 0) { //Go to the beginning of the next line $this->y = $y + $h; if ($ln == 1) { if ($this->rtl) { $this->x = $this->w - $this->rMargin; } else { $this->x = $this->lMargin; } } } else { // go left or right by case if ($this->rtl) { $this->x -= $w; } else { $this->x += $w; } } $gstyles = ''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor."\n"; $rs = $gstyles.$rs; return $rs; } /** * Returns the code to draw the cell border * @param float $x X coordinate. * @param float $y Y coordinate. * @param float $w Cell width. * @param float $h Cell height. * @param mixed $brd Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0))) * @param string $mode border position respect the square edge: normal: centered; ext: external; int: internal; * @return string containing cell border code * @access protected * @see SetLineStyle() * @since 5.7.000 (2010-08-02) */ protected function getCellBorder($x, $y, $w, $h, $brd) { $s = ''; // string to be returned if (empty($brd)) { return $s; } if ($brd == 1) { $brd = array('LRTB' => true); } // calculate coordinates for border $k = $this->k; if ($this->rtl) { $xeL = ($x - $w) * $k; $xeR = $x * $k; } else { $xeL = $x * $k; $xeR = ($x + $w) * $k; } $yeL = (($this->h - ($y + $h)) * $k); $yeT = (($this->h - $y) * $k); $xeT = $xeL; $xeB = $xeR; $yeR = $yeT; $yeB = $yeL; if (is_string($brd)) { // convert string to array $slen = strlen($brd); $newbrd = array(); for ($i = 0; $i < $slen; ++$i) { $newbrd[$brd{$i}] = array('cap' => 'square', 'join' => 'miter'); } $brd = $newbrd; } if (isset($brd['mode'])) { $mode = $brd['mode']; unset($brd['mode']); } else { $mode = 'normal'; } foreach ($brd as $border => $style) { if (is_array($style) AND !empty($style)) { // apply border style $prev_style = $this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '; $s .= $this->SetLineStyle($style, true)."\n"; } switch ($mode) { case 'ext': { $off = (($this->LineWidth / 2) * $k); $xL = $xeL - $off; $xR = $xeR + $off; $yT = $yeT + $off; $yL = $yeL - $off; $xT = $xL; $xB = $xR; $yR = $yT; $yB = $yL; $w += $this->LineWidth; $h += $this->LineWidth; break; } case 'int': { $off = ($this->LineWidth / 2) * $k; $xL = $xeL + $off; $xR = $xeR - $off; $yT = $yeT - $off; $yL = $yeL + $off; $xT = $xL; $xB = $xR; $yR = $yT; $yB = $yL; $w -= $this->LineWidth; $h -= $this->LineWidth; break; } case 'normal': default: { $xL = $xeL; $xT = $xeT; $xB = $xeB; $xR = $xeR; $yL = $yeL; $yT = $yeT; $yB = $yeB; $yR = $yeR; break; } } // draw borders by case if (strlen($border) == 4) { $s .= sprintf('%.2F %.2F %.2F %.2F re S ', $xT, $yT, ($w * $k), (-$h * $k)); } elseif (strlen($border) == 3) { if (strpos($border,'B') === false) { // LTR $s .= sprintf('%.2F %.2F m ', $xL, $yL); $s .= sprintf('%.2F %.2F l ', $xT, $yT); $s .= sprintf('%.2F %.2F l ', $xR, $yR); $s .= sprintf('%.2F %.2F l ', $xB, $yB); $s .= 'S '; } elseif (strpos($border,'L') === false) { // TRB $s .= sprintf('%.2F %.2F m ', $xT, $yT); $s .= sprintf('%.2F %.2F l ', $xR, $yR); $s .= sprintf('%.2F %.2F l ', $xB, $yB); $s .= sprintf('%.2F %.2F l ', $xL, $yL); $s .= 'S '; } elseif (strpos($border,'T') === false) { // RBL $s .= sprintf('%.2F %.2F m ', $xR, $yR); $s .= sprintf('%.2F %.2F l ', $xB, $yB); $s .= sprintf('%.2F %.2F l ', $xL, $yL); $s .= sprintf('%.2F %.2F l ', $xT, $yT); $s .= 'S '; } elseif (strpos($border,'R') === false) { // BLT $s .= sprintf('%.2F %.2F m ', $xB, $yB); $s .= sprintf('%.2F %.2F l ', $xL, $yL); $s .= sprintf('%.2F %.2F l ', $xT, $yT); $s .= sprintf('%.2F %.2F l ', $xR, $yR); $s .= 'S '; } } elseif (strlen($border) == 2) { if ((strpos($border,'L') !== false) AND (strpos($border,'T') !== false)) { // LT $s .= sprintf('%.2F %.2F m ', $xL, $yL); $s .= sprintf('%.2F %.2F l ', $xT, $yT); $s .= sprintf('%.2F %.2F l ', $xR, $yR); $s .= 'S '; } elseif ((strpos($border,'T') !== false) AND (strpos($border,'R') !== false)) { // TR $s .= sprintf('%.2F %.2F m ', $xT, $yT); $s .= sprintf('%.2F %.2F l ', $xR, $yR); $s .= sprintf('%.2F %.2F l ', $xB, $yB); $s .= 'S '; } elseif ((strpos($border,'R') !== false) AND (strpos($border,'B') !== false)) { // RB $s .= sprintf('%.2F %.2F m ', $xR, $yR); $s .= sprintf('%.2F %.2F l ', $xB, $yB); $s .= sprintf('%.2F %.2F l ', $xL, $yL); $s .= 'S '; } elseif ((strpos($border,'B') !== false) AND (strpos($border,'L') !== false)) { // BL $s .= sprintf('%.2F %.2F m ', $xB, $yB); $s .= sprintf('%.2F %.2F l ', $xL, $yL); $s .= sprintf('%.2F %.2F l ', $xT, $yT); $s .= 'S '; } elseif ((strpos($border,'L') !== false) AND (strpos($border,'R') !== false)) { // LR $s .= sprintf('%.2F %.2F m ', $xL, $yL); $s .= sprintf('%.2F %.2F l ', $xT, $yT); $s .= 'S '; $s .= sprintf('%.2F %.2F m ', $xR, $yR); $s .= sprintf('%.2F %.2F l ', $xB, $yB); $s .= 'S '; } elseif ((strpos($border,'T') !== false) AND (strpos($border,'B') !== false)) { // TB $s .= sprintf('%.2F %.2F m ', $xT, $yT); $s .= sprintf('%.2F %.2F l ', $xR, $yR); $s .= 'S '; $s .= sprintf('%.2F %.2F m ', $xB, $yB); $s .= sprintf('%.2F %.2F l ', $xL, $yL); $s .= 'S '; } } else { // strlen($border) == 1 if (strpos($border,'L') !== false) { // L $s .= sprintf('%.2F %.2F m ', $xL, $yL); $s .= sprintf('%.2F %.2F l ', $xT, $yT); $s .= 'S '; } elseif (strpos($border,'T') !== false) { // T $s .= sprintf('%.2F %.2F m ', $xT, $yT); $s .= sprintf('%.2F %.2F l ', $xR, $yR); $s .= 'S '; } elseif (strpos($border,'R') !== false) { // R $s .= sprintf('%.2F %.2F m ', $xR, $yR); $s .= sprintf('%.2F %.2F l ', $xB, $yB); $s .= 'S '; } elseif (strpos($border,'B') !== false) { // B $s .= sprintf('%.2F %.2F m ', $xB, $yB); $s .= sprintf('%.2F %.2F l ', $xL, $yL); $s .= 'S '; } } if (is_array($style) AND !empty($style)) { // reset border style to previous value $s .= "\n".$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor."\n"; } } return $s; } /** * This method allows printing text with line breaks. * They can be automatic (as soon as the text reaches the right border of the cell) or explicit (via the \n character). As many cells as necessary are output, one below the other.<br /> * Text can be aligned, centered or justified. The cell block can be framed and the background painted. * @param float $w Width of cells. If 0, they extend up to the right margin of the page. * @param float $h Cell minimum height. The cell extends automatically if needed. * @param string $txt String to print * @param mixed $border Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0))) * @param string $align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align</li><li>C: center</li><li>R: right align</li><li>J: justification (default value when $ishtml=false)</li></ul> * @param boolean $fill Indicates if the cell background must be painted (true) or transparent (false). * @param int $ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right</li><li>1: to the beginning of the next line [DEFAULT]</li><li>2: below</li></ul> * @param float $x x position in user units * @param float $y y position in user units * @param boolean $reseth if true reset the last cell height (default true). * @param int $stretch stretch carachter mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if necessary</li><li>2 = forced horizontal scaling</li><li>3 = character spacing only if necessary</li><li>4 = forced character spacing</li></ul> * @param boolean $ishtml set to true if $txt is HTML content (default = false). * @param boolean $autopadding if true, uses internal padding and automatically adjust it to account for line width. * @param float $maxh maximum height. It should be >= $h and less then remaining space to the bottom of the page, or 0 for disable this feature. This feature works only when $ishtml=false. * @param string $valign Vertical alignment of text (requires $maxh = $h > 0). Possible values are:<ul><li>T: TOP</li><li>M: middle</li><li>B: bottom</li></ul>. This feature works only when $ishtml=false. * @param boolean $fitcell if true attempt to fit all the text within the cell by reducing the font size. * @return int Return the number of cells or 1 for html mode. * @access public * @since 1.3 * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), Cell(), Write(), SetAutoPageBreak() */ public function MultiCell($w, $h, $txt, $border=0, $align='J', $fill=false, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false, $autopadding=true, $maxh=0, $valign='T', $fitcell=false) { if ($this->empty_string($this->lasth) OR $reseth) { //set row height $this->lasth = $this->FontSize * $this->cell_height_ratio; } if (!$this->empty_string($y)) { $this->SetY($y); } else { $y = $this->GetY(); } $resth = 0; if ((!$this->InFooter) AND (($y + $h) > $this->PageBreakTrigger)) { // spit cell in more pages/columns $newh = $this->PageBreakTrigger - $y; $resth = $h - $newh; // cell to be printed on the next page/column $h = $newh; } // get current page number $startpage = $this->page; // get current column $startcolumn = $this->current_column; if (!$this->empty_string($x)) { $this->SetX($x); } else { $x = $this->GetX(); } if ($this->empty_string($w) OR ($w <= 0)) { if ($this->rtl) { $w = $this->x - $this->lMargin; } else { $w = $this->w - $this->rMargin - $this->x; } } // store original margin values $lMargin = $this->lMargin; $rMargin = $this->rMargin; if ($this->rtl) { $this->SetRightMargin($this->w - $this->x); $this->SetLeftMargin($this->x - $w); } else { $this->SetLeftMargin($this->x); $this->SetRightMargin($this->w - $this->x - $w); } $starty = $this->y; if ($autopadding) { // Adjust internal padding if ($this->cMargin < ($this->LineWidth / 2)) { $this->cMargin = ($this->LineWidth / 2); } // Add top space if needed if (($this->lasth - $this->FontSize) < $this->LineWidth) { $this->y += $this->LineWidth / 2; } // add top padding $this->y += $this->cMargin; } if ($ishtml) { // ******* Write HTML text $this->writeHTML($txt, true, 0, $reseth, true, $align); $nl = 1; } else { // ******* Write simple text // vertical alignment if ($maxh > 0) { // get text height $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, '', ''); if ($fitcell) { $prev_FontSizePt = $this->FontSizePt; // try to reduce font size to fit text on cell (use a quick search algorithm) $fmin = 1; $fmax = $this->FontSizePt; $prev_text_height = $text_height; $maxit = 100; // max number of iterations while ($maxit > 0) { $fmid = (($fmax + $fmin) / 2); $this->SetFontSize($fmid, false); $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, '', ''); if (($text_height == $maxh) OR (($text_height < $maxh) AND ($fmin >= ($fmax - 0.01)))) { break; } elseif ($text_height < $maxh) { $fmin = $fmid; } else { $fmax = $fmid; } --$maxit; } $this->SetFontSize($this->FontSizePt); } if ($text_height < $maxh) { if ($valign == 'M') { // text vertically aligned on middle $this->y += (($maxh - $text_height) / 2); } elseif ($valign == 'B') { // text vertically aligned on bottom $this->y += ($maxh - $text_height); } } } $nl = $this->Write($this->lasth, $txt, '', 0, $align, true, $stretch, false, true, $maxh); if ($fitcell) { // restore font size $this->SetFontSize($prev_FontSizePt); } } if ($autopadding) { // add bottom padding $this->y += $this->cMargin; // Add bottom space if needed if (($this->lasth - $this->FontSize) < $this->LineWidth) { $this->y += $this->LineWidth / 2; } } // Get end-of-text Y position $currentY = $this->y; // get latest page number $endpage = $this->page; if ($resth > 0) { $skip = ($endpage - $startpage); $tmpresth = $resth; while ($tmpresth > 0) { if ($skip <= 0) { // add a page (or trig AcceptPageBreak() for multicolumn mode) $this->checkPageBreak($this->PageBreakTrigger + 1); } if ($this->num_columns > 1) { $tmpresth -= ($this->h - $this->y - $this->bMargin); } else { $tmpresth -= ($this->h - $this->tMargin - $this->bMargin); } --$skip; } $currentY = $this->y; $endpage = $this->page; } // get latest column $endcolumn = $this->current_column; if ($this->num_columns == 0) { $this->num_columns = 1; } // get border modes $border_start = $this->getBorderMode($border, $position='start'); $border_end = $this->getBorderMode($border, $position='end'); $border_middle = $this->getBorderMode($border, $position='middle'); // design borders around HTML cells. for ($page = $startpage; $page <= $endpage; ++$page) { // for each page $ccode = ''; $this->setPage($page); if ($this->num_columns < 2) { // single-column mode $this->SetX($x); $this->y = $this->tMargin; } // account for margin changes if ($page > $startpage) { if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) { $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']); } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) { $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']); } } if ($startpage == $endpage) { // single page for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column $this->selectColumn($column); if ($startcolumn == $endcolumn) { // single column $cborder = $border; $h = max($h, ($currentY - $y)); $this->y = $y; } elseif ($column == $startcolumn) { // first column $cborder = $border_start; $this->y = $starty; $h = $this->h - $this->y - $this->bMargin; } elseif ($column == $endcolumn) { // end column $cborder = $border_end; $h = $currentY - $this->y; if ($resth > $h) { $h = $resth; } } else { // middle column $cborder = $border_middle; $h = $this->h - $this->y - $this->bMargin; $resth -= $h; } $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n"; } // end for each column } elseif ($page == $startpage) { // first page for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column $this->selectColumn($column); if ($column == $startcolumn) { // first column $cborder = $border_start; $this->y = $starty; $h = $this->h - $this->y - $this->bMargin; } else { // middle column $cborder = $border_middle; $h = $this->h - $this->y - $this->bMargin; $resth -= $h; } $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n"; } // end for each column } elseif ($page == $endpage) { // last page for ($column = 0; $column <= $endcolumn; ++$column) { // for each column $this->selectColumn($column); if ($column == $endcolumn) { // end column $cborder = $border_end; $h = $currentY - $this->y; if ($resth > $h) { $h = $resth; } } else { // middle column $cborder = $border_middle; $h = $this->h - $this->y - $this->bMargin; $resth -= $h; } $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n"; } // end for each column } else { // middle page for ($column = 0; $column < $this->num_columns; ++$column) { // for each column $this->selectColumn($column); $cborder = $border_middle; $h = $this->h - $this->y - $this->bMargin; $resth -= $h; $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n"; } // end for each column } if ($cborder OR $fill) { // draw border and fill if (end($this->transfmrk[$this->page]) !== false) { $pagemarkkey = key($this->transfmrk[$this->page]); $pagemark = &$this->transfmrk[$this->page][$pagemarkkey]; } elseif ($this->InFooter) { $pagemark = &$this->footerpos[$this->page]; } else { $pagemark = &$this->intmrk[$this->page]; } $pagebuff = $this->getPageBuffer($this->page); $pstart = substr($pagebuff, 0, $pagemark); $pend = substr($pagebuff, $pagemark); $this->setPageBuffer($this->page, $pstart.$ccode.$pend); $pagemark += strlen($ccode); } } // end for each page // Get end-of-cell Y position $currentY = $this->GetY(); // restore original margin values $this->SetLeftMargin($lMargin); $this->SetRightMargin($rMargin); if ($ln > 0) { //Go to the beginning of the next line $this->SetY($currentY); if ($ln == 2) { $this->SetX($x + $w); } } else { // go left or right by case $this->setPage($startpage); $this->y = $y; $this->SetX($x + $w); } $this->setContentMark(); return $nl; } /** * Get the border mode accounting for multicell position (opens bottom side of multicell crossing pages) * @param mixed $brd Indicates if borders must be drawn around the cell block. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0))) * @param string multicell position: 'start', 'middle', 'end' * @return border mode array * @access protected * @since 4.4.002 (2008-12-09) */ protected function getBorderMode($brd, $position='start') { if ((!$this->opencell) OR empty($brd)) { return $brd; } if ($brd == 1) { $brd = 'LTRB'; } if (is_string($brd)) { // convert string to array $slen = strlen($brd); $newbrd = array(); for ($i = 0; $i < $slen; ++$i) { $newbrd[$brd{$i}] = array('cap' => 'square', 'join' => 'miter'); } $brd = $newbrd; } foreach ($brd as $border => $style) { switch ($position) { case 'start': { if (strpos($border, 'B') !== false) { // remove bottom line $newkey = str_replace('B', '', $border); if (strlen($newkey) > 0) { $brd[$newkey] = $style; } unset($brd[$border]); } break; } case 'middle': { if (strpos($border, 'B') !== false) { // remove bottom line $newkey = str_replace('B', '', $border); if (strlen($newkey) > 0) { $brd[$newkey] = $style; } unset($brd[$border]); $border = $newkey; } if (strpos($border, 'T') !== false) { // remove bottom line $newkey = str_replace('T', '', $border); if (strlen($newkey) > 0) { $brd[$newkey] = $style; } unset($brd[$border]); } break; } case 'end': { if (strpos($border, 'T') !== false) { // remove bottom line $newkey = str_replace('T', '', $border); if (strlen($newkey) > 0) { $brd[$newkey] = $style; } unset($brd[$border]); } break; } } } return $brd; } /** * This method return the estimated number of lines for print a simple text string in Multicell() method. * @param string $txt String for calculating his height * @param float $w Width of cells. If 0, they extend up to the right margin of the page. * @param boolean $reseth if true reset the last cell height (default false). * @param boolean $autopadding if true, uses internal padding and automatically adjust it to account for line width (default true). * @param float $cellMargin Internal cell margin, if empty or <= 0, extended up to current pdf cell margin (default ''). * @param float $lineWidth Line width, if empty or <= 0, extended up to current pdf line width (default ''). * @return float Return the minimal height needed for multicell method for printing the $txt param. * @author Alexander Escalona Fernández, Nicola Asuni * @access public * @since 4.5.011 */ public function getNumLines($txt, $w=0, $reseth=false, $autopadding=true, $cellMargin='', $lineWidth='') { if ($this->empty_string($w) OR ($w <= 0)) { if ($this->rtl) { $w = $this->x - $this->lMargin; } else { $w = $this->w - $this->rMargin - $this->x; } } if ($this->empty_string($cellMargin) OR ($cellMargin <= 0)) { $cellMargin = $this->cMargin; } if ($this->empty_string($lineWidth) OR ($lineWidth <= 0)) { $lineWidth = $this->LineWidth; } if ($autopadding) { // adjust internal padding if ($cellMargin < ($lineWidth/2)) { $cellMargin = ($lineWidth/2); } } $wmax = $w - (2 * $cellMargin); if ($reseth) { $this->lasth = $this->FontSize * $this->cell_height_ratio; } $lines = 1; $sum = 0; $chars = $this->utf8Bidi($this->UTF8StringToArray($txt), $txt, $this->tmprtl); $charsWidth = $this->GetArrStringWidth($chars, '', '', 0, true); $length = count($chars); $lastSeparator = -1; for ($i = 0; $i < $length; ++$i) { $charWidth = $charsWidth[$i]; if (preg_match($this->re_spaces, $this->unichr($chars[$i]))) { $lastSeparator = $i; } if ((($sum + $charWidth) > $wmax) OR ($chars[$i] == 10)) { ++$lines; if ($lastSeparator != -1) { $i = $lastSeparator; $lastSeparator = -1; $sum = 0; } else { $sum = $charWidth; } } else { $sum += $charWidth; } } if ($chars[($length - 1)] == 10) { --$lines; } return $lines; } /** * This method return the estimated needed height for print a simple text string in Multicell() method. * Generally, if you want to know the exact height for a block of content you can use the following alternative technique: * <pre> * // store current object * $pdf->startTransaction(); * // store starting values * $start_y = $pdf->GetY(); * $start_page = $pdf->getPage(); * // call your printing functions with your parameters * // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * $pdf->MultiCell($w=0, $h=0, $txt, $border=1, $align='L', $fill=false, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false, $autopadding=true, $maxh=0); * // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * // get the new Y * $end_y = $pdf->GetY(); * $end_page = $pdf->getPage(); * // calculate height * $height = 0; * if ($end_page == $start_page) { * $height = $end_y - $start_y; * } else { * for ($page=$start_page; $page <= $end_page; ++$page) { * $this->setPage($page); * if ($page == $start_page) { * // first page * $height = $this->h - $start_y - $this->bMargin; * } elseif ($page == $end_page) { * // last page * $height = $end_y - $this->tMargin; * } else { * $height = $this->h - $this->tMargin - $this->bMargin; * } * } * } * // restore previous object * $pdf = $pdf->rollbackTransaction(); * </pre> * @param float $w Width of cells. If 0, they extend up to the right margin of the page. * @param string $txt String for calculating his height * @param boolean $reseth if true reset the last cell height (default false). * @param boolean $autopadding if true, uses internal padding and automatically adjust it to account for line width (default true). * @param float $cellMargin Internal cell margin, if empty or <= 0, extended up to current pdf cell margin (default ''). * @param float $lineWidth Line width, if empty or <= 0, extended up to current pdf line width (default ''). * @return float Return the minimal height needed for multicell method for printing the $txt param. * @author Nicola Asuni, Alexander Escalona Fernández * @access public */ public function getStringHeight($w, $txt, $reseth=false, $autopadding=true, $cellMargin='', $lineWidth='') { $lines = $this->getNumLines($txt, $w, $reseth, $autopadding, $cellMargin, $lineWidth); $height = $lines * ($this->FontSize * $this->cell_height_ratio); if ($autopadding) { if ($this->empty_string($cellMargin) OR ($cellMargin <= 0)) { $cellMargin = $this->cMargin; } if ($this->empty_string($lineWidth) OR ($lineWidth <= 0)) { $lineWidth = $this->LineWidth; } // adjust internal padding if ($cellMargin < ($lineWidth/2)) { $cellMargin = ($lineWidth/2); } // add top and bottom space if needed if (($this->lasth - $this->FontSize) < $lineWidth) { $height += $lineWidth; } // add top and bottom padding $height += (2 * $cellMargin); } return $height; } /** * This method prints text from the current position.<br /> * @param float $h Line height * @param string $txt String to print * @param mixed $link URL or identifier returned by AddLink() * @param boolean $fill Indicates if the cell background must be painted (true) or transparent (false). * @param string $align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul> * @param boolean $ln if true set cursor at the bottom of the line, otherwise set cursor at the top of the line. * @param int $stretch stretch carachter mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if necessary</li><li>2 = forced horizontal scaling</li><li>3 = character spacing only if necessary</li><li>4 = forced character spacing</li></ul> * @param boolean $firstline if true prints only the first line and return the remaining string. * @param boolean $firstblock if true the string is the starting of a line. * @param float $maxh maximum height. The remaining unprinted text will be returned. It should be >= $h and less then remaining space to the bottom of the page, or 0 for disable this feature. * @param float $wadj first line width will be reduced by this amount (used in HTML mode). * @return mixed Return the number of cells or the remaining string if $firstline = true. * @access public * @since 1.5 */ public function Write($h, $txt, $link='', $fill=false, $align='', $ln=false, $stretch=0, $firstline=false, $firstblock=false, $maxh=0, $wadj=0) { if (strlen($txt) == 0) { $txt = ' '; } // remove carriage returns $s = str_replace("\r", '', $txt); // check if string contains arabic text if (preg_match(K_RE_PATTERN_ARABIC, $s)) { $arabic = true; } else { $arabic = false; } // check if string contains RTL text if ($arabic OR ($this->tmprtl == 'R') OR preg_match(K_RE_PATTERN_RTL, $s)) { $rtlmode = true; } else { $rtlmode = false; } // get a char width $chrwidth = $this->GetCharWidth('.'); // get array of unicode values $chars = $this->UTF8StringToArray($s); // get array of chars $uchars = $this->UTF8ArrayToUniArray($chars); // get the number of characters $nb = count($chars); // replacement for SHY character (minus symbol) $shy_replacement = 45; $shy_replacement_char = $this->unichr($shy_replacement); // widht for SHY replacement $shy_replacement_width = $this->GetCharWidth($shy_replacement); // max Y $maxy = $this->y + $maxh - $h - (2 * $this->cMargin); // calculate remaining line width ($w) if ($this->rtl) { $w = $this->x - $this->lMargin; } else { $w = $this->w - $this->rMargin - $this->x; } // max column width $wmax = $w - (2 * $this->cMargin) - $wadj; if ((!$firstline) AND (($chrwidth > $wmax) OR ($this->GetCharWidth($chars[0]) > $wmax))) { // a single character do not fit on column return ''; } // minimum row height $row_height = max($h, $this->FontSize * $this->cell_height_ratio); $start_page = $this->page; $i = 0; // character position $j = 0; // current starting position $sep = -1; // position of the last blank space $shy = false; // true if the last blank is a soft hypen (SHY) $l = 0; // current string length $nl = 0; //number of lines $linebreak = false; $pc = 0; // previous character // for each character while ($i < $nb) { if (($maxh > 0) AND ($this->y >= $maxy) ) { break; } //Get the current character $c = $chars[$i]; if ($c == 10) { // 10 = "\n" = new line //Explicit line break if ($align == 'J') { if ($this->rtl) { $talign = 'R'; } else { $talign = 'L'; } } else { $talign = $align; } $tmpstr = $this->UniArrSubString($uchars, $j, $i); if ($firstline) { $startx = $this->x; $tmparr = array_slice($chars, $j, ($i - $j)); if ($rtlmode) { $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl); } $linew = $this->GetArrStringWidth($tmparr); unset($tmparr); if ($this->rtl) { $this->endlinex = $startx - $linew; } else { $this->endlinex = $startx + $linew; } $w = $linew; $tmpcmargin = $this->cMargin; if ($maxh == 0) { $this->cMargin = 0; } } if ($firstblock AND $this->isRTLTextDir()) { $tmpstr = $this->stringRightTrim($tmpstr); } // Skip newlines at the begining of a page or column if (!empty($tmpstr) OR ($this->y < ($this->PageBreakTrigger - $row_height))) { $this->Cell($w, $h, $tmpstr, 0, 1, $talign, $fill, $link, $stretch); } unset($tmpstr); if ($firstline) { $this->cMargin = $tmpcmargin; return ($this->UniArrSubString($uchars, $i)); } ++$nl; $j = $i + 1; $l = 0; $sep = -1; $shy = false; // account for margin changes if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND (!$this->InFooter)) { $this->AcceptPageBreak(); } $w = $this->getRemainingWidth(); $wmax = $w - (2 * $this->cMargin); } else { // 160 is the non-breaking space. // 173 is SHY (Soft Hypen). // \p{Z} or \p{Separator}: any kind of Unicode whitespace or invisible separator. // \p{Lo} or \p{Other_Letter}: a Unicode letter or ideograph that does not have lowercase and uppercase variants. // \p{Lo} is needed because Chinese characters are packed next to each other without spaces in between. if (($c != 160) AND (($c == 173) OR preg_match($this->re_spaces, $this->unichr($c)))) { // update last blank space position $sep = $i; // check if is a SHY if ($c == 173) { $shy = true; if ($pc == 45) { $tmp_shy_replacement_width = 0; $tmp_shy_replacement_char = ''; } else { $tmp_shy_replacement_width = $shy_replacement_width; $tmp_shy_replacement_char = $shy_replacement_char; } } else { $shy = false; } } // update string length if ($this->isUnicodeFont() AND ($arabic)) { // with bidirectional algorithm some chars may be changed affecting the line length // *** very slow *** $l = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, ($i - $j)), '', $this->tmprtl)); } else { $l += $this->GetCharWidth($c); } if (($l > $wmax) OR (($c == 173) AND (($l + $tmp_shy_replacement_width) > $wmax)) ) { // we have reached the end of column if ($sep == -1) { // check if the line was already started if (($this->rtl AND ($this->x <= ($this->w - $this->rMargin - $chrwidth))) OR ((!$this->rtl) AND ($this->x >= ($this->lMargin + $chrwidth)))) { // print a void cell and go to next line $this->Cell($w, $h, '', 0, 1); $linebreak = true; if ($firstline) { return ($this->UniArrSubString($uchars, $j)); } } else { // truncate the word because do not fit on column $tmpstr = $this->UniArrSubString($uchars, $j, $i); if ($firstline) { $startx = $this->x; $tmparr = array_slice($chars, $j, ($i - $j)); if ($rtlmode) { $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl); } $linew = $this->GetArrStringWidth($tmparr); unset($tmparr); if ($this->rtl) { $this->endlinex = $startx - $linew; } else { $this->endlinex = $startx + $linew; } $w = $linew; $tmpcmargin = $this->cMargin; if ($maxh == 0) { $this->cMargin = 0; } } if ($firstblock AND $this->isRTLTextDir()) { $tmpstr = $this->stringRightTrim($tmpstr); } $this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch); unset($tmpstr); if ($firstline) { $this->cMargin = $tmpcmargin; return ($this->UniArrSubString($uchars, $i)); } $j = $i; --$i; } } else { // word wrapping if ($this->rtl AND (!$firstblock) AND ($sep < $i)) { $endspace = 1; } else { $endspace = 0; } if ($shy) { // add hypen (minus symbol) at the end of the line $shy_width = $tmp_shy_replacement_width; if ($this->rtl) { $shy_char_left = $tmp_shy_replacement_char; $shy_char_right = ''; } else { $shy_char_left = ''; $shy_char_right = $tmp_shy_replacement_char; } } else { $shy_width = 0; $shy_char_left = ''; $shy_char_right = ''; } $tmpstr = $this->UniArrSubString($uchars, $j, ($sep + $endspace)); if ($firstline) { $startx = $this->x; $tmparr = array_slice($chars, $j, (($sep + $endspace) - $j)); if ($rtlmode) { $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl); } $linew = $this->GetArrStringWidth($tmparr); unset($tmparr); if ($this->rtl) { $this->endlinex = $startx - $linew - $shy_width; } else { $this->endlinex = $startx + $linew + $shy_width; } $w = $linew; $tmpcmargin = $this->cMargin; if ($maxh == 0) { $this->cMargin = 0; } } // print the line if ($firstblock AND $this->isRTLTextDir()) { $tmpstr = $this->stringRightTrim($tmpstr); } $this->Cell($w, $h, $shy_char_left.$tmpstr.$shy_char_right, 0, 1, $align, $fill, $link, $stretch); unset($tmpstr); if ($firstline) { // return the remaining text $this->cMargin = $tmpcmargin; return ($this->UniArrSubString($uchars, ($sep + $endspace))); } $i = $sep; $sep = -1; $shy = false; $j = ($i+1); } // account for margin changes if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND (!$this->InFooter)) { $this->AcceptPageBreak(); } $w = $this->getRemainingWidth(); $wmax = $w - (2 * $this->cMargin); if ($linebreak) { $linebreak = false; } else { ++$nl; $l = 0; } } } // save last character $pc = $c; ++$i; } // end while i < nb // print last substring (if any) if ($l > 0) { switch ($align) { case 'J': case 'C': { $w = $w; break; } case 'L': { if ($this->rtl) { $w = $w; } else { $w = $l; } break; } case 'R': { if ($this->rtl) { $w = $l; } else { $w = $w; } break; } default: { $w = $l; break; } } $tmpstr = $this->UniArrSubString($uchars, $j, $nb); if ($firstline) { $startx = $this->x; $tmparr = array_slice($chars, $j, ($nb - $j)); if ($rtlmode) { $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl); } $linew = $this->GetArrStringWidth($tmparr); unset($tmparr); if ($this->rtl) { $this->endlinex = $startx - $linew; } else { $this->endlinex = $startx + $linew; } $w = $linew; $tmpcmargin = $this->cMargin; if ($maxh == 0) { $this->cMargin = 0; } } if ($firstblock AND $this->isRTLTextDir()) { $tmpstr = $this->stringRightTrim($tmpstr); } $this->Cell($w, $h, $tmpstr, 0, $ln, $align, $fill, $link, $stretch); unset($tmpstr); if ($firstline) { $this->cMargin = $tmpcmargin; return ($this->UniArrSubString($uchars, $nb)); } ++$nl; } if ($firstline) { return ''; } return $nl; } /** * Returns the remaining width between the current position and margins. * @return int Return the remaining width * @access protected */ protected function getRemainingWidth() { if ($this->rtl) { return ($this->x - $this->lMargin); } else { return ($this->w - $this->rMargin - $this->x); } } /** * Extract a slice of the $strarr array and return it as string. * @param string $strarr The input array of characters. * @param int $start the starting element of $strarr. * @param int $end first element that will not be returned. * @return Return part of a string * @access public */ public function UTF8ArrSubString($strarr, $start='', $end='') { if (strlen($start) == 0) { $start = 0; } if (strlen($end) == 0) { $end = count($strarr); } $string = ''; for ($i=$start; $i < $end; ++$i) { $string .= $this->unichr($strarr[$i]); } return $string; } /** * Extract a slice of the $uniarr array and return it as string. * @param string $uniarr The input array of characters. * @param int $start the starting element of $strarr. * @param int $end first element that will not be returned. * @return Return part of a string * @access public * @since 4.5.037 (2009-04-07) */ public function UniArrSubString($uniarr, $start='', $end='') { if (strlen($start) == 0) { $start = 0; } if (strlen($end) == 0) { $end = count($uniarr); } $string = ''; for ($i=$start; $i < $end; ++$i) { $string .= $uniarr[$i]; } return $string; } /** * Convert an array of UTF8 values to array of unicode characters * @param string $ta The input array of UTF8 values. * @return Return array of unicode characters * @access public * @since 4.5.037 (2009-04-07) */ public function UTF8ArrayToUniArray($ta) { return array_map(array($this, 'unichr'), $ta); } /** * Returns the unicode caracter specified by UTF-8 value * @param int $c UTF-8 value * @return Returns the specified character. * @author Miguel Perez, Nicola Asuni * @access public * @since 2.3.000 (2008-03-05) */ public function unichr($c) { if (!$this->isunicode) { return chr($c); } elseif ($c <= 0x7F) { // one byte return chr($c); } elseif ($c <= 0x7FF) { // two bytes return chr(0xC0 | $c >> 6).chr(0x80 | $c & 0x3F); } elseif ($c <= 0xFFFF) { // three bytes return chr(0xE0 | $c >> 12).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F); } elseif ($c <= 0x10FFFF) { // four bytes return chr(0xF0 | $c >> 18).chr(0x80 | $c >> 12 & 0x3F).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F); } else { return ''; } } /** * Return the image type given the file name or array returned by getimagesize() function. * @param string $imgfile image file name * @param array $iminfo array of image information returned by getimagesize() function. * @return string image type * @since 4.8.017 (2009-11-27) */ public function getImageFileType($imgfile, $iminfo=array()) { $type = ''; if (isset($iminfo['mime']) AND !empty($iminfo['mime'])) { $mime = explode('/', $iminfo['mime']); if ((count($mime) > 1) AND ($mime[0] == 'image') AND (!empty($mime[1]))) { $type = strtolower(trim($mime[1])); } } if (empty($type)) { $fileinfo = pathinfo($imgfile); if (isset($fileinfo['extension']) AND (!$this->empty_string($fileinfo['extension']))) { $type = strtolower(trim($fileinfo['extension'])); } } if ($type == 'jpg') { $type = 'jpeg'; } return $type; } /** * Set the block dimensions accounting for page breaks and page/column fitting * @param float $w width * @param float $h height * @param float $x X coordinate * @param float $y Y coodiante * @param boolean $fitonpage if true the block is resized to not exceed page dimensions. * @access protected * @since 5.5.009 (2010-07-05) */ protected function fitBlock(&$w, &$h, &$x, &$y, $fitonpage=false) { // resize the block to be vertically contained on a single page or single column if ($fitonpage OR $this->AutoPageBreak) { $ratio_wh = ($w / $h); if ($h > ($this->PageBreakTrigger - $this->tMargin)) { $h = $this->PageBreakTrigger - $this->tMargin; $w = ($h * $ratio_wh); } // resize the block to be horizontally contained on a single page or single column if ($fitonpage) { $maxw = ($this->w - $this->lMargin - $this->rMargin); if ($w > $maxw) { $w = $maxw; $h = ($w / $ratio_wh); } } } // Check whether we need a new page or new column first as this does not fit $prev_x = $this->x; $prev_y = $this->y; if ($this->checkPageBreak($h, $y) OR ($this->y < $prev_y)) { $y = $this->y; if ($this->rtl) { $x += ($prev_x - $this->x); } else { $x += ($this->x - $prev_x); } } // resize the block to be contained on the remaining available page or column space if ($fitonpage) { $ratio_wh = ($w / $h); if (($y + $h) > $this->PageBreakTrigger) { $h = $this->PageBreakTrigger - $y; $w = ($h * $ratio_wh); } if ((!$this->rtl) AND (($x + $w) > ($this->w - $this->rMargin))) { $w = $this->w - $this->rMargin - $x; $h = ($w / $ratio_wh); } elseif (($this->rtl) AND (($x - $w) < ($this->lMargin))) { $w = $x - $this->lMargin; $h = ($w / $ratio_wh); } } } /** * Puts an image in the page. * The upper-left corner must be given. * The dimensions can be specified in different ways:<ul> * <li>explicit width and height (expressed in user unit)</li> * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li> * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul> * Supported formats are JPEG and PNG images whitout GD library and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM; * The format can be specified explicitly or inferred from the file extension.<br /> * It is possible to put a link on the image.<br /> * Remark: if an image is used several times, only one copy will be embedded in the file.<br /> * @param string $file Name of the file containing the image. * @param float $x Abscissa of the upper-left corner (LTR) or upper-right corner (RTL). * @param float $y Ordinate of the upper-left corner (LTR) or upper-right corner (RTL). * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated. * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated. * @param string $type Image format. Possible values are (case insensitive): JPEG and PNG (whitout GD library) and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;. If not specified, the type is inferred from the file extension. * @param mixed $link URL or identifier returned by AddLink(). * @param string $align Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul> * @param mixed $resize If true resize (reduce) the image to fit $w and $h (requires GD or ImageMagick library); if false do not resize; if 2 force resize in all cases (upscaling and downscaling). * @param int $dpi dot-per-inch resolution used on resize * @param string $palign Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul> * @param boolean $ismask true if this image is a mask, false otherwise * @param mixed $imgmask image object returned by this function or false * @param mixed $border Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0))) * @param boolean $fitbox If true scale image dimensions proportionally to fit within the ($w, $h) box. * @param boolean $hidden if true do not display the image. * @param boolean $fitonpage if true the image is resized to not exceed page dimensions. * @return image information * @access public * @since 1.1 */ public function Image($file, $x='', $y='', $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='', $ismask=false, $imgmask=false, $border=0, $fitbox=false, $hidden=false, $fitonpage=false) { if ($x === '') { $x = $this->x; } if ($y === '') { $y = $this->y; } $cached_file = false; // true when the file is cached // get image dimensions $imsize = @getimagesize($file); if ($imsize === FALSE) { // try to encode spaces on filename $file = str_replace(' ', '%20', $file); $imsize = @getimagesize($file); if ($imsize === FALSE) { if (function_exists('curl_init')) { // try to get remote file data using cURL $cs = curl_init(); // curl session curl_setopt($cs, CURLOPT_URL, $file); curl_setopt($cs, CURLOPT_BINARYTRANSFER, true); curl_setopt($cs, CURLOPT_FAILONERROR, true); curl_setopt($cs, CURLOPT_RETURNTRANSFER, true); curl_setopt($cs, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($cs, CURLOPT_TIMEOUT, 30); $imgdata = curl_exec($cs); curl_close($cs); if($imgdata !== FALSE) { // copy image to cache $file = tempnam(K_PATH_CACHE, 'img_'); $fp = fopen($file, 'w'); fwrite($fp, $imgdata); fclose($fp); unset($imgdata); $cached_file = true; $imsize = @getimagesize($file); if ($imsize === FALSE) { unlink($file); $cached_file = false; } } } elseif (($w > 0) AND ($h > 0)) { // get measures from specified data $pw = $this->getHTMLUnitToUnits($w, 0, $this->pdfunit, true) * $this->imgscale * $this->k; $ph = $this->getHTMLUnitToUnits($h, 0, $this->pdfunit, true) * $this->imgscale * $this->k; $imsize = array($pw, $ph); } } } if ($imsize === FALSE) { $this->Error('[Image] Unable to get image: '.$file); } // get original image width and height in pixels list($pixw, $pixh) = $imsize; // calculate image width and height on document if (($w <= 0) AND ($h <= 0)) { // convert image size to document unit $w = $this->pixelsToUnits($pixw); $h = $this->pixelsToUnits($pixh); } elseif ($w <= 0) { $w = $h * $pixw / $pixh; } elseif ($h <= 0) { $h = $w * $pixh / $pixw; } elseif ($fitbox AND ($w > 0) AND ($h > 0)) { // scale image dimensions proportionally to fit within the ($w, $h) box if ((($w * $pixh) / ($h * $pixw)) < 1) { $h = $w * $pixh / $pixw; } else { $w = $h * $pixw / $pixh; } } // fit the image on available space $this->fitBlock($w, $h, $x, $y, $fitonpage); // calculate new minimum dimensions in pixels $neww = round($w * $this->k * $dpi / $this->dpi); $newh = round($h * $this->k * $dpi / $this->dpi); // check if resize is necessary (resize is used only to reduce the image) $newsize = ($neww * $newh); $pixsize = ($pixw * $pixh); if (intval($resize) == 2) { $resize = true; } elseif ($newsize >= $pixsize) { $resize = false; } // check if image has been already added on document $newimage = true; if (in_array($file, $this->imagekeys)) { $newimage = false; // get existing image data $info = $this->getImageBuffer($file); // check if the newer image is larger $oldsize = ($info['w'] * $info['h']); if ((($oldsize < $newsize) AND ($resize)) OR (($oldsize < $pixsize) AND (!$resize))) { $newimage = true; } } if ($newimage) { //First use of image, get info $type = strtolower($type); if ($type == '') { $type = $this->getImageFileType($file, $imsize); } elseif ($type == 'jpg') { $type = 'jpeg'; } $mqr = $this->get_mqr(); $this->set_mqr(false); // Specific image handlers $mtd = '_parse'.$type; // GD image handler function $gdfunction = 'imagecreatefrom'.$type; $info = false; if ((method_exists($this, $mtd)) AND (!($resize AND function_exists($gdfunction)))) { // TCPDF image functions $info = $this->$mtd($file); if ($info == 'pngalpha') { return $this->ImagePngAlpha($file, $x, $y, $pixw, $pixh, $w, $h, 'PNG', $link, $align, $resize, $dpi, $palign); } } if (!$info) { if (function_exists($gdfunction)) { // GD library $img = $gdfunction($file); if ($resize) { $imgr = imagecreatetruecolor($neww, $newh); if (($type == 'gif') OR ($type == 'png')) { $imgr = $this->_setGDImageTransparency($imgr, $img); } imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh); if (($type == 'gif') OR ($type == 'png')) { $info = $this->_toPNG($imgr); } else { $info = $this->_toJPEG($imgr); } } else { if (($type == 'gif') OR ($type == 'png')) { $info = $this->_toPNG($img); } else { $info = $this->_toJPEG($img); } } } elseif (extension_loaded('imagick')) { // ImageMagick library $img = new Imagick(); if ($type == 'SVG') { // get SVG file content $svgimg = file_get_contents($file); // get width and height $regs = array(); if (preg_match('/<svg([^\>]*)>/si', $svgimg, $regs)) { $svgtag = $regs[1]; $tmp = array(); if (preg_match('/[\s]+width[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) { $ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false); $owu = sprintf('%.3F', ($ow * $dpi / 72)).$this->pdfunit; $svgtag = preg_replace('/[\s]+width[\s]*=[\s]*"[^"]*"/si', ' width="'.$owu.'"', $svgtag, 1); } else { $ow = $w; } $tmp = array(); if (preg_match('/[\s]+height[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) { $oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false); $ohu = sprintf('%.3F', ($oh * $dpi / 72)).$this->pdfunit; $svgtag = preg_replace('/[\s]+height[\s]*=[\s]*"[^"]*"/si', ' height="'.$ohu.'"', $svgtag, 1); } else { $oh = $h; } $tmp = array(); if (!preg_match('/[\s]+viewBox[\s]*=[\s]*"[\s]*([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]*"/si', $svgtag, $tmp)) { $vbw = ($ow * $this->imgscale * $this->k); $vbh = ($oh * $this->imgscale * $this->k); $vbox = sprintf(' viewBox="0 0 %.3F %.3F" ', $vbw, $vbh); $svgtag = $vbox.$svgtag; } $svgimg = preg_replace('/<svg([^\>]*)>/si', '<svg'.$svgtag.'>', $svgimg, 1); } $img->readImageBlob($svgimg); } else { $img->readImage($file); } if ($resize) { $img->resizeImage($neww, $newh, 10, 1, false); } $img->setCompressionQuality($this->jpeg_quality); $img->setImageFormat('jpeg'); $tempname = tempnam(K_PATH_CACHE, 'jpg_'); $img->writeImage($tempname); $info = $this->_parsejpeg($tempname); unlink($tempname); $img->destroy(); } else { return; } } if ($info === false) { //If false, we cannot process image return; } $this->set_mqr($mqr); if ($ismask) { // force grayscale $info['cs'] = 'DeviceGray'; } $info['i'] = $this->numimages; if (!in_array($file, $this->imagekeys)) { ++$info['i']; } if ($imgmask !== false) { $info['masked'] = $imgmask; } // add image to document $this->setImageBuffer($file, $info); } if ($cached_file) { // remove cached file unlink($file); } // set alignment $this->img_rb_y = $y + $h; // set alignment if ($this->rtl) { if ($palign == 'L') { $ximg = $this->lMargin; } elseif ($palign == 'C') { $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2; } elseif ($palign == 'R') { $ximg = $this->w - $this->rMargin - $w; } else { $ximg = $x - $w; } $this->img_rb_x = $ximg; } else { if ($palign == 'L') { $ximg = $this->lMargin; } elseif ($palign == 'C') { $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2; } elseif ($palign == 'R') { $ximg = $this->w - $this->rMargin - $w; } else { $ximg = $x; } $this->img_rb_x = $ximg + $w; } if ($ismask OR $hidden) { // image is not displayed return $info['i']; } $xkimg = $ximg * $this->k; $this->_out(sprintf('q %.2F 0 0 %.2F %.2F %.2F cm /I%u Do Q', ($w * $this->k), ($h * $this->k), $xkimg, (($this->h - ($y + $h)) * $this->k), $info['i'])); if (!empty($border)) { $bx = $this->x; $by = $this->y; $this->x = $ximg; if ($this->rtl) { $this->x += $w; } $this->y = $y; $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true); $this->x = $bx; $this->y = $by; } if ($link) { $this->Link($ximg, $y, $w, $h, $link, 0); } // set pointer to align the next text/objects switch($align) { case 'T': { $this->y = $y; $this->x = $this->img_rb_x; break; } case 'M': { $this->y = $y + round($h/2); $this->x = $this->img_rb_x; break; } case 'B': { $this->y = $this->img_rb_y; $this->x = $this->img_rb_x; break; } case 'N': { $this->SetY($this->img_rb_y); break; } default:{ break; } } $this->endlinex = $this->img_rb_x; if ($this->inxobj) { // we are inside an XObject template $this->xobjects[$this->xobjid]['images'][] = $info['i']; } return $info['i']; } /** * Sets the current active configuration setting of magic_quotes_runtime (if the set_magic_quotes_runtime function exist) * @param boolean $mqr FALSE for off, TRUE for on. * @since 4.6.025 (2009-08-17) */ public function set_mqr($mqr) { if(!defined('PHP_VERSION_ID')) { $version = PHP_VERSION; define('PHP_VERSION_ID', (($version{0} * 10000) + ($version{2} * 100) + $version{4})); } if (PHP_VERSION_ID < 50300) { @set_magic_quotes_runtime($mqr); } } /** * Gets the current active configuration setting of magic_quotes_runtime (if the get_magic_quotes_runtime function exist) * @return Returns 0 if magic quotes runtime is off or get_magic_quotes_runtime doesn't exist, 1 otherwise. * @since 4.6.025 (2009-08-17) */ public function get_mqr() { if(!defined('PHP_VERSION_ID')) { $version = PHP_VERSION; define('PHP_VERSION_ID', (($version{0} * 10000) + ($version{2} * 100) + $version{4})); } if (PHP_VERSION_ID < 50300) { return @get_magic_quotes_runtime(); } return 0; } /** * Convert the loaded image to a JPEG and then return a structure for the PDF creator. * This function requires GD library and write access to the directory defined on K_PATH_CACHE constant. * @param string $file Image file name. * @param image $image Image object. * return image JPEG image object. * @access protected */ protected function _toJPEG($image) { $tempname = tempnam(K_PATH_CACHE, 'jpg_'); imagejpeg($image, $tempname, $this->jpeg_quality); imagedestroy($image); $retvars = $this->_parsejpeg($tempname); // tidy up by removing temporary image unlink($tempname); return $retvars; } /** * Convert the loaded image to a PNG and then return a structure for the PDF creator. * This function requires GD library and write access to the directory defined on K_PATH_CACHE constant. * @param string $file Image file name. * @param image $image Image object. * return image PNG image object. * @access protected * @since 4.9.016 (2010-04-20) */ protected function _toPNG($image) { $tempname = tempnam(K_PATH_CACHE, 'jpg_'); imagepng($image, $tempname); imagedestroy($image); $retvars = $this->_parsepng($tempname); // tidy up by removing temporary image unlink($tempname); return $retvars; } /** * Set the transparency for the given GD image. * @param image $new_image GD image object * @param image $image GD image object. * return GD image object. * @access protected * @since 4.9.016 (2010-04-20) */ protected function _setGDImageTransparency($new_image, $image) { // transparency index $tid = imagecolortransparent($image); // default transparency color $tcol = array('red' => 255, 'green' => 255, 'blue' => 255); if ($tid >= 0) { // get the colors for the transparency index $tcol = imagecolorsforindex($image, $tid); } $tid = imagecolorallocate($new_image, $tcol['red'], $tcol['green'], $tcol['blue']); imagefill($new_image, 0, 0, $tid); imagecolortransparent($new_image, $tid); return $new_image; } /** * Extract info from a JPEG file without using the GD library. * @param string $file image file to parse * @return array structure containing the image data * @access protected */ protected function _parsejpeg($file) { $a = getimagesize($file); if (empty($a)) { $this->Error('Missing or incorrect image file: '.$file); } if ($a[2] != 2) { $this->Error('Not a JPEG file: '.$file); } if ((!isset($a['channels'])) OR ($a['channels'] == 3)) { $colspace = 'DeviceRGB'; } elseif ($a['channels'] == 4) { $colspace = 'DeviceCMYK'; } else { $colspace = 'DeviceGray'; } $bpc = isset($a['bits']) ? $a['bits'] : 8; $data = file_get_contents($file); return array('w' => $a[0], 'h' => $a[1], 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'DCTDecode', 'data' => $data); } /** * Extract info from a PNG file without using the GD library. * @param string $file image file to parse * @return array structure containing the image data * @access protected */ protected function _parsepng($file) { $f = fopen($file, 'rb'); if ($f === false) { $this->Error('Can\'t open image file: '.$file); } //Check signature if (fread($f, 8) != chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) { $this->Error('Not a PNG file: '.$file); } //Read header chunk fread($f, 4); if (fread($f, 4) != 'IHDR') { $this->Error('Incorrect PNG file: '.$file); } $w = $this->_freadint($f); $h = $this->_freadint($f); $bpc = ord(fread($f, 1)); if ($bpc > 8) { //$this->Error('16-bit depth not supported: '.$file); fclose($f); return false; } $ct = ord(fread($f, 1)); if ($ct == 0) { $colspace = 'DeviceGray'; } elseif ($ct == 2) { $colspace = 'DeviceRGB'; } elseif ($ct == 3) { $colspace = 'Indexed'; } else { // alpha channel fclose($f); return 'pngalpha'; } if (ord(fread($f, 1)) != 0) { //$this->Error('Unknown compression method: '.$file); fclose($f); return false; } if (ord(fread($f, 1)) != 0) { //$this->Error('Unknown filter method: '.$file); fclose($f); return false; } if (ord(fread($f, 1)) != 0) { //$this->Error('Interlacing not supported: '.$file); fclose($f); return false; } fread($f, 4); $parms = '/DecodeParms << /Predictor 15 /Colors '.($ct == 2 ? 3 : 1).' /BitsPerComponent '.$bpc.' /Columns '.$w.' >>'; //Scan chunks looking for palette, transparency and image data $pal = ''; $trns = ''; $data = ''; do { $n = $this->_freadint($f); $type = fread($f, 4); if ($type == 'PLTE') { //Read palette $pal = $this->rfread($f, $n); fread($f, 4); } elseif ($type == 'tRNS') { //Read transparency info $t = $this->rfread($f, $n); if ($ct == 0) { $trns = array(ord(substr($t, 1, 1))); } elseif ($ct == 2) { $trns = array(ord(substr($t, 1, 1)), ord(substr($t, 3, 1)), ord(substr($t, 5, 1))); } else { $pos = strpos($t, chr(0)); if ($pos !== false) { $trns = array($pos); } } fread($f, 4); } elseif ($type == 'IDAT') { //Read image data block $data .= $this->rfread($f, $n); fread($f, 4); } elseif ($type == 'IEND') { break; } else { $this->rfread($f, $n + 4); } } while ($n); if (($colspace == 'Indexed') AND (empty($pal))) { //$this->Error('Missing palette in '.$file); fclose($f); return false; } fclose($f); return array('w' => $w, 'h' => $h, 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'FlateDecode', 'parms' => $parms, 'pal' => $pal, 'trns' => $trns, 'data' => $data); } /** * Binary-safe and URL-safe file read. * Reads up to length bytes from the file pointer referenced by handle. Reading stops as soon as one of the following conditions is met: length bytes have been read; EOF (end of file) is reached. * @param resource $handle * @param int $length * @return Returns the read string or FALSE in case of error. * @author Nicola Asuni * @access protected * @since 4.5.027 (2009-03-16) */ protected function rfread($handle, $length) { $data = fread($handle, $length); if ($data === false) { return false; } $rest = $length - strlen($data); if ($rest > 0) { $data .= $this->rfread($handle, $rest); } return $data; } /** * Extract info from a PNG image with alpha channel using the GD library. * @param string $file Name of the file containing the image. * @param float $x Abscissa of the upper-left corner. * @param float $y Ordinate of the upper-left corner. * @param float $wpx Original width of the image in pixels. * @param float $hpx original height of the image in pixels. * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated. * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated. * @param string $type Image format. Possible values are (case insensitive): JPEG and PNG (whitout GD library) and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;. If not specified, the type is inferred from the file extension. * @param mixed $link URL or identifier returned by AddLink(). * @param string $align Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul> * @param boolean $resize If true resize (reduce) the image to fit $w and $h (requires GD library). * @param int $dpi dot-per-inch resolution used on resize * @param string $palign Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul> * @author Valentin Schmidt, Nicola Asuni * @access protected * @since 4.3.007 (2008-12-04) * @see Image() */ protected function ImagePngAlpha($file, $x, $y, $wpx, $hpx, $w, $h, $type, $link, $align, $resize, $dpi, $palign) { // generate images $img = imagecreatefrompng($file); $imgalpha = imagecreate($wpx, $hpx); // generate gray scale palette (0 -> 255) for ($c = 0; $c < 256; ++$c) { ImageColorAllocate($imgalpha, $c, $c, $c); } // extract alpha channel for ($xpx = 0; $xpx < $wpx; ++$xpx) { for ($ypx = 0; $ypx < $hpx; ++$ypx) { $color = imagecolorat($img, $xpx, $ypx); $alpha = ($color >> 24); // shifts off the first 24 bits (where 8x3 are used for each color), and returns the remaining 7 allocated bits (commonly used for alpha) $alpha = (((127 - $alpha) / 127) * 255); // GD alpha is only 7 bit (0 -> 127) $alpha = $this->getGDgamma($alpha); // correct gamma imagesetpixel($imgalpha, $xpx, $ypx, $alpha); } } // create temp alpha file $tempfile_alpha = tempnam(K_PATH_CACHE, 'mska_'); imagepng($imgalpha, $tempfile_alpha); imagedestroy($imgalpha); // extract image without alpha channel $imgplain = imagecreatetruecolor($wpx, $hpx); imagecopy($imgplain, $img, 0, 0, 0, 0, $wpx, $hpx); // create temp image file $tempfile_plain = tempnam(K_PATH_CACHE, 'mskp_'); imagepng($imgplain, $tempfile_plain); imagedestroy($imgplain); // embed mask image $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false); // embed image, masked with previously embedded mask $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask); // remove temp files unlink($tempfile_alpha); unlink($tempfile_plain); } /** * Correct the gamma value to be used with GD library * @param float $v the gamma value to be corrected * @access protected * @since 4.3.007 (2008-12-04) */ protected function getGDgamma($v) { return (pow(($v / 255), 2.2) * 255); } /** * Performs a line break. * The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter. * @param float $h The height of the break. By default, the value equals the height of the last printed cell. * @param boolean $cell if true add a cMargin to the x coordinate * @access public * @since 1.0 * @see Cell() */ public function Ln($h='', $cell=false) { if (($this->num_columns > 1) AND ($this->y == $this->columns[$this->current_column]['y']) AND isset($this->columns[$this->current_column]['x']) AND ($this->x == $this->columns[$this->current_column]['x'])) { // revove vertical space from the top of the column return; } if ($cell) { $cellmargin = $this->cMargin; } else { $cellmargin = 0; } if ($this->rtl) { $this->x = $this->w - $this->rMargin - $cellmargin; } else { $this->x = $this->lMargin + $cellmargin; } if (is_string($h)) { $this->y += $this->lasth; } else { $this->y += $h; } $this->newline = true; } /** * Returns the relative X value of current position. * The value is relative to the left border for LTR languages and to the right border for RTL languages. * @return float * @access public * @since 1.2 * @see SetX(), GetY(), SetY() */ public function GetX() { //Get x position if ($this->rtl) { return ($this->w - $this->x); } else { return $this->x; } } /** * Returns the absolute X value of current position. * @return float * @access public * @since 1.2 * @see SetX(), GetY(), SetY() */ public function GetAbsX() { return $this->x; } /** * Returns the ordinate of the current position. * @return float * @access public * @since 1.0 * @see SetY(), GetX(), SetX() */ public function GetY() { return $this->y; } /** * Defines the abscissa of the current position. * If the passed value is negative, it is relative to the right of the page (or left if language is RTL). * @param float $x The value of the abscissa. * @param boolean $rtloff if true always uses the page top-left corner as origin of axis. * @access public * @since 1.2 * @see GetX(), GetY(), SetY(), SetXY() */ public function SetX($x, $rtloff=false) { if (!$rtloff AND $this->rtl) { if ($x >= 0) { $this->x = $this->w - $x; } else { $this->x = abs($x); } } else { if ($x >= 0) { $this->x = $x; } else { $this->x = $this->w + $x; } } if ($this->x < 0) { $this->x = 0; } if ($this->x > $this->w) { $this->x = $this->w; } } /** * Moves the current abscissa back to the left margin and sets the ordinate. * If the passed value is negative, it is relative to the bottom of the page. * @param float $y The value of the ordinate. * @param bool $resetx if true (default) reset the X position. * @param boolean $rtloff if true always uses the page top-left corner as origin of axis. * @access public * @since 1.0 * @see GetX(), GetY(), SetY(), SetXY() */ public function SetY($y, $resetx=true, $rtloff=false) { if ($resetx) { //reset x if (!$rtloff AND $this->rtl) { $this->x = $this->w - $this->rMargin; } else { $this->x = $this->lMargin; } } if ($y >= 0) { $this->y = $y; } else { $this->y = $this->h + $y; } if ($this->y < 0) { $this->y = 0; } if ($this->y > $this->h) { $this->y = $this->h; } } /** * Defines the abscissa and ordinate of the current position. * If the passed values are negative, they are relative respectively to the right and bottom of the page. * @param float $x The value of the abscissa. * @param float $y The value of the ordinate. * @param boolean $rtloff if true always uses the page top-left corner as origin of axis. * @access public * @since 1.2 * @see SetX(), SetY() */ public function SetXY($x, $y, $rtloff=false) { $this->SetY($y, false, $rtloff); $this->SetX($x, $rtloff); } /** * Send the document to a given destination: string, local file or browser. * In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br /> * The method first calls Close() if necessary to terminate the document. * @param string $name The name of the file when saved. Note that special characters are removed and blanks characters are replaced with the underscore character. * @param string $dest Destination where to send the document. It can take one of the following values:<ul><li>I: send the file inline to the browser (default). The plug-in is used if available. The name given by name is used when one selects the "Save as" option on the link generating the PDF.</li><li>D: send to the browser and force a file download with the name given by name.</li><li>F: save to a local server file with the name given by name.</li><li>S: return the document as a string. name is ignored.</li><li>FI: equivalent to F + I option</li><li>FD: equivalent to F + D option</li></ul> * @access public * @since 1.0 * @see Close() */ public function Output($name='doc.pdf', $dest='I') { //Output PDF to some destination //Finish document if necessary if ($this->state < 3) { $this->Close(); } //Normalize parameters if (is_bool($dest)) { $dest = $dest ? 'D' : 'F'; } $dest = strtoupper($dest); if ($dest{0} != 'F') { $name = preg_replace('/[\s]+/', '_', $name); $name = preg_replace('/[^a-zA-Z0-9_\.-]/', '', $name); } if ($this->sign) { // *** apply digital signature to the document *** // get the document content $pdfdoc = $this->getBuffer(); // remove last newline $pdfdoc = substr($pdfdoc, 0, -1); // Remove the original buffer if (isset($this->diskcache) AND $this->diskcache) { // remove buffer file from cache unlink($this->buffer); } unset($this->buffer); // remove filler space $byterange_string_len = strlen($this->byterange_string); // define the ByteRange $byte_range = array(); $byte_range[0] = 0; $byte_range[1] = strpos($pdfdoc, $this->byterange_string) + $byterange_string_len + 10; $byte_range[2] = $byte_range[1] + $this->signature_max_length + 2; $byte_range[3] = strlen($pdfdoc) - $byte_range[2]; $pdfdoc = substr($pdfdoc, 0, $byte_range[1]).substr($pdfdoc, $byte_range[2]); // replace the ByteRange $byterange = sprintf('/ByteRange[0 %u %u %u]', $byte_range[1], $byte_range[2], $byte_range[3]); $byterange .= str_repeat(' ', ($byterange_string_len - strlen($byterange))); $pdfdoc = str_replace($this->byterange_string, $byterange, $pdfdoc); // write the document to a temporary folder $tempdoc = tempnam(K_PATH_CACHE, 'tmppdf_'); $f = fopen($tempdoc, 'wb'); if (!$f) { $this->Error('Unable to create temporary file: '.$tempdoc); } $pdfdoc_length = strlen($pdfdoc); fwrite($f, $pdfdoc, $pdfdoc_length); fclose($f); // get digital signature via openssl library $tempsign = tempnam(K_PATH_CACHE, 'tmpsig_'); if (empty($this->signature_data['extracerts'])) { openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data['signcert'], array($this->signature_data['privkey'], $this->signature_data['password']), array(), PKCS7_BINARY | PKCS7_DETACHED); } else { openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data['signcert'], array($this->signature_data['privkey'], $this->signature_data['password']), array(), PKCS7_BINARY | PKCS7_DETACHED, $this->signature_data['extracerts']); } unlink($tempdoc); // read signature $signature = file_get_contents($tempsign); unlink($tempsign); // extract signature $signature = substr($signature, $pdfdoc_length); $signature = substr($signature, (strpos($signature, "%%EOF\n\n------") + 13)); $tmparr = explode("\n\n", $signature); $signature = $tmparr[1]; unset($tmparr); // decode signature $signature = base64_decode(trim($signature)); // convert signature to hex $signature = current(unpack('H*', $signature)); $signature = str_pad($signature, $this->signature_max_length, '0'); // Add signature to the document $pdfdoc = substr($pdfdoc, 0, $byte_range[1]).'<'.$signature.'>'.substr($pdfdoc, $byte_range[1]); $this->diskcache = false; $this->buffer = &$pdfdoc; $this->bufferlen = strlen($pdfdoc); } switch($dest) { case 'I': { // Send PDF to the standard output if (ob_get_contents()) { $this->Error('Some data has already been output, can\'t send PDF file'); } if (php_sapi_name() != 'cli') { //We send to a browser header('Content-Type: application/pdf'); if (headers_sent()) { $this->Error('Some data has already been output to browser, can\'t send PDF file'); } header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1 header('Pragma: public'); header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); header('Content-Length: '.$this->bufferlen); header('Content-Disposition: inline; filename="'.basename($name).'";'); } echo $this->getBuffer(); break; } case 'D': { // Download PDF as file if (ob_get_contents()) { $this->Error('Some data has already been output, can\'t send PDF file'); } header('Content-Description: File Transfer'); if (headers_sent()) { $this->Error('Some data has already been output to browser, can\'t send PDF file'); } header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1 header('Pragma: public'); header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // force download dialog header('Content-Type: application/force-download'); header('Content-Type: application/octet-stream', false); header('Content-Type: application/download', false); header('Content-Type: application/pdf', false); // use the Content-Disposition header to supply a recommended filename header('Content-Disposition: attachment; filename="'.basename($name).'";'); header('Content-Transfer-Encoding: binary'); header('Content-Length: '.$this->bufferlen); echo $this->getBuffer(); break; } case 'F': case 'FI': case 'FD': { // Save PDF to a local file if ($this->diskcache) { copy($this->buffer, $name); } else { $f = fopen($name, 'wb'); if (!$f) { $this->Error('Unable to create output file: '.$name); } fwrite($f, $this->getBuffer(), $this->bufferlen); fclose($f); } if ($dest == 'FI') { // send headers to browser header('Content-Type: application/pdf'); header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1 header('Pragma: public'); header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); header('Content-Length: '.filesize($name)); header('Content-Disposition: inline; filename="'.basename($name).'";'); // send document to the browser echo file_get_contents($name); } elseif ($dest == 'FD') { // send headers to browser if (ob_get_contents()) { $this->Error('Some data has already been output, can\'t send PDF file'); } header('Content-Description: File Transfer'); if (headers_sent()) { $this->Error('Some data has already been output to browser, can\'t send PDF file'); } header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1 header('Pragma: public'); header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // force download dialog header('Content-Type: application/force-download'); header('Content-Type: application/octet-stream', false); header('Content-Type: application/download', false); header('Content-Type: application/pdf', false); // use the Content-Disposition header to supply a recommended filename header('Content-Disposition: attachment; filename="'.basename($name).'";'); header('Content-Transfer-Encoding: binary'); header('Content-Length: '.filesize($name)); // send document to the browser echo file_get_contents($name); } break; } case 'S': { // Returns PDF as a string return $this->getBuffer(); } default: { $this->Error('Incorrect output destination: '.$dest); } } return ''; } /** * Unset all class variables except the following critical variables: internal_encoding, state, bufferlen, buffer and diskcache. * @param boolean $destroyall if true destroys all class variables, otherwise preserves critical variables. * @param boolean $preserve_objcopy if true preserves the objcopy variable * @access public * @since 4.5.016 (2009-02-24) */ public function _destroy($destroyall=false, $preserve_objcopy=false) { if ($destroyall AND isset($this->diskcache) AND $this->diskcache AND (!$preserve_objcopy) AND (!$this->empty_string($this->buffer))) { // remove buffer file from cache unlink($this->buffer); } foreach (array_keys(get_object_vars($this)) as $val) { if ($destroyall OR ( ($val != 'internal_encoding') AND ($val != 'state') AND ($val != 'bufferlen') AND ($val != 'buffer') AND ($val != 'diskcache') AND ($val != 'sign') AND ($val != 'signature_data') AND ($val != 'signature_max_length') AND ($val != 'byterange_string') )) { if ((!$preserve_objcopy OR ($val != 'objcopy')) AND isset($this->$val)) { unset($this->$val); } } } } /** * Check for locale-related bug * @access protected */ protected function _dochecks() { //Check for locale-related bug if (1.1 == 1) { $this->Error('Don\'t alter the locale before including class file'); } //Check for decimal separator if (sprintf('%.1F', 1.0) != '1.0') { setlocale(LC_NUMERIC, 'C'); } } /** * Return fonts path * @return string * @access protected */ protected function _getfontpath() { if (!defined('K_PATH_FONTS') AND is_dir(dirname(__FILE__).'/fonts')) { define('K_PATH_FONTS', dirname(__FILE__).'/fonts/'); } return defined('K_PATH_FONTS') ? K_PATH_FONTS : ''; } /** * Output pages. * @access protected */ protected function _putpages() { $nb = $this->numpages; if (!empty($this->AliasNbPages)) { $nbs = $this->formatPageNumber($nb); $nbu = $this->UTF8ToUTF16BE($nbs, false); // replacement for unicode font $alias_a = $this->_escape($this->AliasNbPages); $alias_au = $this->_escape('{'.$this->AliasNbPages.'}'); if ($this->isunicode) { $alias_b = $this->_escape($this->UTF8ToLatin1($this->AliasNbPages)); $alias_bu = $this->_escape($this->UTF8ToLatin1('{'.$this->AliasNbPages.'}')); $alias_c = $this->_escape($this->utf8StrRev($this->AliasNbPages, false, $this->tmprtl)); $alias_cu = $this->_escape($this->utf8StrRev('{'.$this->AliasNbPages.'}', false, $this->tmprtl)); } } if (!empty($this->AliasNumPage)) { $alias_pa = $this->_escape($this->AliasNumPage); $alias_pau = $this->_escape('{'.$this->AliasNumPage.'}'); if ($this->isunicode) { $alias_pb = $this->_escape($this->UTF8ToLatin1($this->AliasNumPage)); $alias_pbu = $this->_escape($this->UTF8ToLatin1('{'.$this->AliasNumPage.'}')); $alias_pc = $this->_escape($this->utf8StrRev($this->AliasNumPage, false, $this->tmprtl)); $alias_pcu = $this->_escape($this->utf8StrRev('{'.$this->AliasNumPage.'}', false, $this->tmprtl)); } } $pagegroupnum = 0; $filter = ($this->compress) ? '/Filter /FlateDecode ' : ''; for ($n=1; $n <= $nb; ++$n) { $temppage = $this->getPageBuffer($n); if (!empty($this->pagegroups)) { if(isset($this->newpagegroup[$n])) { $pagegroupnum = 0; } ++$pagegroupnum; foreach ($this->pagegroups as $k => $v) { // replace total pages group numbers $vs = $this->formatPageNumber($v); $vu = $this->UTF8ToUTF16BE($vs, false); $alias_ga = $this->_escape($k); $alias_gau = $this->_escape('{'.$k.'}'); if ($this->isunicode) { $alias_gb = $this->_escape($this->UTF8ToLatin1($k)); $alias_gbu = $this->_escape($this->UTF8ToLatin1('{'.$k.'}')); $alias_gc = $this->_escape($this->utf8StrRev($k, false, $this->tmprtl)); $alias_gcu = $this->_escape($this->utf8StrRev('{'.$k.'}', false, $this->tmprtl)); } $temppage = str_replace($alias_gau, $vu, $temppage); if ($this->isunicode) { $temppage = str_replace($alias_gbu, $vu, $temppage); $temppage = str_replace($alias_gcu, $vu, $temppage); $temppage = str_replace($alias_gb, $vs, $temppage); $temppage = str_replace($alias_gc, $vs, $temppage); } $temppage = str_replace($alias_ga, $vs, $temppage); // replace page group numbers $pvs = $this->formatPageNumber($pagegroupnum); $pvu = $this->UTF8ToUTF16BE($pvs, false); $pk = str_replace('{nb', '{pnb', $k); $alias_pga = $this->_escape($pk); $alias_pgau = $this->_escape('{'.$pk.'}'); if ($this->isunicode) { $alias_pgb = $this->_escape($this->UTF8ToLatin1($pk)); $alias_pgbu = $this->_escape($this->UTF8ToLatin1('{'.$pk.'}')); $alias_pgc = $this->_escape($this->utf8StrRev($pk, false, $this->tmprtl)); $alias_pgcu = $this->_escape($this->utf8StrRev('{'.$pk.'}', false, $this->tmprtl)); } $temppage = str_replace($alias_pgau, $pvu, $temppage); if ($this->isunicode) { $temppage = str_replace($alias_pgbu, $pvu, $temppage); $temppage = str_replace($alias_pgcu, $pvu, $temppage); $temppage = str_replace($alias_pgb, $pvs, $temppage); $temppage = str_replace($alias_pgc, $pvs, $temppage); } $temppage = str_replace($alias_pga, $pvs, $temppage); } } if (!empty($this->AliasNbPages)) { // replace total pages number $temppage = str_replace($alias_au, $nbu, $temppage); if ($this->isunicode) { $temppage = str_replace($alias_bu, $nbu, $temppage); $temppage = str_replace($alias_cu, $nbu, $temppage); $temppage = str_replace($alias_b, $nbs, $temppage); $temppage = str_replace($alias_c, $nbs, $temppage); } $temppage = str_replace($alias_a, $nbs, $temppage); } if (!empty($this->AliasNumPage)) { // replace page number $pnbs = $this->formatPageNumber($n); $pnbu = $this->UTF8ToUTF16BE($pnbs, false); // replacement for unicode font $temppage = str_replace($alias_pau, $pnbu, $temppage); if ($this->isunicode) { $temppage = str_replace($alias_pbu, $pnbu, $temppage); $temppage = str_replace($alias_pcu, $pnbu, $temppage); $temppage = str_replace($alias_pb, $pnbs, $temppage); $temppage = str_replace($alias_pc, $pnbs, $temppage); } $temppage = str_replace($alias_pa, $pnbs, $temppage); } $temppage = str_replace($this->epsmarker, '', $temppage); //Page $this->page_obj_id[$n] = $this->_newobj(); $out = '<<'; $out .= ' /Type /Page'; $out .= ' /Parent 1 0 R'; $out .= ' /LastModified '.$this->_datestring(); $out .= ' /Resources 2 0 R'; $boxes = array('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox'); foreach ($boxes as $box) { $out .= ' /'.$box; $out .= sprintf(' [%.2F %.2F %.2F %.2F]', $this->pagedim[$n][$box]['llx'], $this->pagedim[$n][$box]['lly'], $this->pagedim[$n][$box]['urx'], $this->pagedim[$n][$box]['ury']); } if (isset($this->pagedim[$n]['BoxColorInfo']) AND !empty($this->pagedim[$n]['BoxColorInfo'])) { $out .= ' /BoxColorInfo <<'; foreach ($boxes as $box) { if (isset($this->pagedim[$n]['BoxColorInfo'][$box])) { $out .= ' /'.$box.' <<'; if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['C'])) { $color = $this->pagedim[$n]['BoxColorInfo'][$box]['C']; $out .= ' /C ['; $out .= sprintf(' %.3F %.3F %.3F', $color[0]/255, $color[1]/255, $color[2]/255); $out .= ' ]'; } if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['W'])) { $out .= ' /W '.($this->pagedim[$n]['BoxColorInfo'][$box]['W'] * $this->k); } if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['S'])) { $out .= ' /S /'.$this->pagedim[$n]['BoxColorInfo'][$box]['S']; } if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['D'])) { $dashes = $this->pagedim[$n]['BoxColorInfo'][$box]['D']; $out .= ' /D ['; foreach ($dashes as $dash) { $out .= sprintf(' %.3F', ($dash * $this->k)); } $out .= ' ]'; } $out .= ' >>'; } } $out .= ' >>'; } $out .= ' /Contents '.($this->n + 1).' 0 R'; $out .= ' /Rotate '.$this->pagedim[$n]['Rotate']; $out .= ' /Group << /Type /Group /S /Transparency /CS /DeviceRGB >>'; if (isset($this->pagedim[$n]['trans']) AND !empty($this->pagedim[$n]['trans'])) { // page transitions if (isset($this->pagedim[$n]['trans']['Dur'])) { $out .= ' /Dur '.$this->pagedim[$n]['trans']['Dur']; } $out .= ' /Trans <<'; $out .= ' /Type /Trans'; if (isset($this->pagedim[$n]['trans']['S'])) { $out .= ' /S /'.$this->pagedim[$n]['trans']['S']; } if (isset($this->pagedim[$n]['trans']['D'])) { $out .= ' /D '.$this->pagedim[$n]['trans']['D']; } if (isset($this->pagedim[$n]['trans']['Dm'])) { $out .= ' /Dm /'.$this->pagedim[$n]['trans']['Dm']; } if (isset($this->pagedim[$n]['trans']['M'])) { $out .= ' /M /'.$this->pagedim[$n]['trans']['M']; } if (isset($this->pagedim[$n]['trans']['Di'])) { $out .= ' /Di '.$this->pagedim[$n]['trans']['Di']; } if (isset($this->pagedim[$n]['trans']['SS'])) { $out .= ' /SS '.$this->pagedim[$n]['trans']['SS']; } if (isset($this->pagedim[$n]['trans']['B'])) { $out .= ' /B '.$this->pagedim[$n]['trans']['B']; } $out .= ' >>'; } $out .= $this->_getannotsrefs($n); $out .= ' /PZ '.$this->pagedim[$n]['PZ']; $out .= ' >>'; $out .= "\n".'endobj'; $this->_out($out); //Page content $p = ($this->compress) ? gzcompress($temppage) : $temppage; $this->_newobj(); $p = $this->_getrawstream($p); $this->_out('<<'.$filter.'/Length '.strlen($p).'>> stream'."\n".$p."\n".'endstream'."\n".'endobj'); if ($this->diskcache) { // remove temporary files unlink($this->pages[$n]); } } //Pages root $out = $this->_getobj(1)."\n"; $out .= '<< /Type /Pages /Kids ['; foreach($this->page_obj_id as $page_obj) { $out .= ' '.$page_obj.' 0 R'; } $out .= ' ] /Count '.$nb.' >>'; $out .= "\n".'endobj'; $this->_out($out); } /** * Output references to page annotations * @param int $n page number * @access protected * @author Nicola Asuni * @since 4.7.000 (2008-08-29) * @deprecated */ protected function _putannotsrefs($n) { $this->_out(_getannotsrefs($n)); } /** * Get references to page annotations. * @param int $n page number * @return string * @access protected * @author Nicola Asuni * @since 5.0.010 (2010-05-17) */ protected function _getannotsrefs($n) { if (!(isset($this->PageAnnots[$n]) OR ($this->sign AND isset($this->signature_data['cert_type'])))) { return ''; } $out = ' /Annots ['; if (isset($this->PageAnnots[$n])) { foreach ($this->PageAnnots[$n] as $key => $val) { if (!in_array($val['n'], $this->radio_groups)) { $out .= ' '.$val['n'].' 0 R'; } } // add radiobutton groups if (isset($this->radiobutton_groups[$n])) { foreach ($this->radiobutton_groups[$n] as $key => $data) { if (isset($data['n'])) { $out .= ' '.$data['n'].' 0 R'; } } } } if ($this->sign AND ($n == $this->signature_appearance['page']) AND isset($this->signature_data['cert_type'])) { // set reference for signature object $out .= ' '.$this->sig_obj_id.' 0 R'; } $out .= ' ]'; return $out; } /** * Output annotations objects for all pages. * !!! THIS METHOD IS NOT YET COMPLETED !!! * See section 12.5 of PDF 32000_2008 reference. * @access protected * @author Nicola Asuni * @since 4.0.018 (2008-08-06) */ protected function _putannotsobjs() { // reset object counter for ($n=1; $n <= $this->numpages; ++$n) { if (isset($this->PageAnnots[$n])) { // set page annotations foreach ($this->PageAnnots[$n] as $key => $pl) { $annot_obj_id = $this->PageAnnots[$n][$key]['n']; // create annotation object for grouping radiobuttons if (isset($this->radiobutton_groups[$n][$pl['txt']]) AND is_array($this->radiobutton_groups[$n][$pl['txt']])) { $radio_button_obj_id = $this->radiobutton_groups[$n][$pl['txt']]['n']; $annots = '<<'; $annots .= ' /Type /Annot'; $annots .= ' /Subtype /Widget'; $annots .= ' /Rect [0 0 0 0]'; $annots .= ' /T '.$this->_datastring($pl['txt'], $radio_button_obj_id); $annots .= ' /FT /Btn'; $annots .= ' /Ff 49152'; $annots .= ' /Kids ['; foreach ($this->radiobutton_groups[$n][$pl['txt']] as $key => $data) { if ($key !== 'n') { $annots .= ' '.$data['kid'].' 0 R'; if ($data['def'] !== 'Off') { $defval = $data['def']; } } } $annots .= ' ]'; if (isset($defval)) { $annots .= ' /V /'.$defval; } $annots .= ' >>'; $this->_out($this->_getobj($radio_button_obj_id)."\n".$annots."\n".'endobj'); $this->form_obj_id[] = $radio_button_obj_id; // store object id to be used on Parent entry of Kids $this->radiobutton_groups[$n][$pl['txt']] = $radio_button_obj_id; } $formfield = false; $pl['opt'] = array_change_key_case($pl['opt'], CASE_LOWER); $a = $pl['x'] * $this->k; $b = $this->pagedim[$n]['h'] - (($pl['y'] + $pl['h']) * $this->k); $c = $pl['w'] * $this->k; $d = $pl['h'] * $this->k; $rect = sprintf('%.2F %.2F %.2F %.2F', $a, $b, $a+$c, $b+$d); // create new annotation object $annots = '<</Type /Annot'; $annots .= ' /Subtype /'.$pl['opt']['subtype']; $annots .= ' /Rect ['.$rect.']'; $ft = array('Btn', 'Tx', 'Ch', 'Sig'); if (isset($pl['opt']['ft']) AND in_array($pl['opt']['ft'], $ft)) { $annots .= ' /FT /'.$pl['opt']['ft']; $formfield = true; } $annots .= ' /Contents '.$this->_textstring($pl['txt'], $annot_obj_id); $annots .= ' /P '.$this->page_obj_id[$n].' 0 R'; $annots .= ' /NM '.$this->_datastring(sprintf('%04u-%04u', $n, $key), $annot_obj_id); $annots .= ' /M '.$this->_datestring($annot_obj_id); if (isset($pl['opt']['f'])) { $val = 0; if (is_array($pl['opt']['f'])) { foreach ($pl['opt']['f'] as $f) { switch (strtolower($f)) { case 'invisible': { $val += 1 << 0; break; } case 'hidden': { $val += 1 << 1; break; } case 'print': { $val += 1 << 2; break; } case 'nozoom': { $val += 1 << 3; break; } case 'norotate': { $val += 1 << 4; break; } case 'noview': { $val += 1 << 5; break; } case 'readonly': { $val += 1 << 6; break; } case 'locked': { $val += 1 << 8; break; } case 'togglenoview': { $val += 1 << 9; break; } case 'lockedcontents': { $val += 1 << 10; break; } default: { break; } } } } else { $val = intval($pl['opt']['f']); } $annots .= ' /F '.intval($val); } if (isset($pl['opt']['as']) AND is_string($pl['opt']['as'])) { $annots .= ' /AS /'.$pl['opt']['as']; } if (isset($pl['opt']['ap'])) { // appearance stream $annots .= ' /AP <<'; if (is_array($pl['opt']['ap'])) { foreach ($pl['opt']['ap'] as $apmode => $apdef) { // $apmode can be: n = normal; r = rollover; d = down; $annots .= ' /'.strtoupper($apmode); if (is_array($apdef)) { $annots .= ' <<'; foreach ($apdef as $apstate => $stream) { // reference to XObject that define the appearance for this mode-state $apsobjid = $this->_putAPXObject($c, $d, $stream); $annots .= ' /'.$apstate.' '.$apsobjid.' 0 R'; } $annots .= ' >>'; } else { // reference to XObject that define the appearance for this mode $apsobjid = $this->_putAPXObject($c, $d, $apdef); $annots .= ' '.$apsobjid.' 0 R'; } } } else { $annots .= $pl['opt']['ap']; } $annots .= ' >>'; } if (isset($pl['opt']['bs']) AND (is_array($pl['opt']['bs']))) { $annots .= ' /BS <<'; $annots .= ' /Type /Border'; if (isset($pl['opt']['bs']['w'])) { $annots .= ' /W '.intval($pl['opt']['bs']['w']); } $bstyles = array('S', 'D', 'B', 'I', 'U'); if (isset($pl['opt']['bs']['s']) AND in_array($pl['opt']['bs']['s'], $bstyles)) { $annots .= ' /S /'.$pl['opt']['bs']['s']; } if (isset($pl['opt']['bs']['d']) AND (is_array($pl['opt']['bs']['d']))) { $annots .= ' /D ['; foreach ($pl['opt']['bs']['d'] as $cord) { $annots .= ' '.intval($cord); } $annots .= ']'; } $annots .= ' >>'; } else { $annots .= ' /Border ['; if (isset($pl['opt']['border']) AND (count($pl['opt']['border']) >= 3)) { $annots .= intval($pl['opt']['border'][0]).' '; $annots .= intval($pl['opt']['border'][1]).' '; $annots .= intval($pl['opt']['border'][2]); if (isset($pl['opt']['border'][3]) AND is_array($pl['opt']['border'][3])) { $annots .= ' ['; foreach ($pl['opt']['border'][3] as $dash) { $annots .= intval($dash).' '; } $annots .= ']'; } } else { $annots .= '0 0 0'; } $annots .= ']'; } if (isset($pl['opt']['be']) AND (is_array($pl['opt']['be']))) { $annots .= ' /BE <<'; $bstyles = array('S', 'C'); if (isset($pl['opt']['be']['s']) AND in_array($pl['opt']['be']['s'], $markups)) { $annots .= ' /S /'.$pl['opt']['bs']['s']; } else { $annots .= ' /S /S'; } if (isset($pl['opt']['be']['i']) AND ($pl['opt']['be']['i'] >= 0) AND ($pl['opt']['be']['i'] <= 2)) { $annots .= ' /I '.sprintf(' %.4F', $pl['opt']['be']['i']); } $annots .= '>>'; } if (isset($pl['opt']['c']) AND (is_array($pl['opt']['c'])) AND !empty($pl['opt']['c'])) { $annots .= ' /C ['; foreach ($pl['opt']['c'] as $col) { $col = intval($col); $color = $col <= 0 ? 0 : ($col >= 255 ? 1 : $col / 255); $annots .= sprintf(' %.4F', $color); } $annots .= ']'; } //$annots .= ' /StructParent '; //$annots .= ' /OC '; $markups = array('text', 'freetext', 'line', 'square', 'circle', 'polygon', 'polyline', 'highlight', 'underline', 'squiggly', 'strikeout', 'stamp', 'caret', 'ink', 'fileattachment', 'sound'); if (in_array(strtolower($pl['opt']['subtype']), $markups)) { // this is a markup type if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) { $annots .= ' /T '.$this->_textstring($pl['opt']['t'], $annot_obj_id); } //$annots .= ' /Popup '; if (isset($pl['opt']['ca'])) { $annots .= ' /CA '.sprintf('%.4F', floatval($pl['opt']['ca'])); } if (isset($pl['opt']['rc'])) { $annots .= ' /RC '.$this->_textstring($pl['opt']['rc'], $annot_obj_id); } $annots .= ' /CreationDate '.$this->_datestring($annot_obj_id); //$annots .= ' /IRT '; if (isset($pl['opt']['subj'])) { $annots .= ' /Subj '.$this->_textstring($pl['opt']['subj'], $annot_obj_id); } //$annots .= ' /RT '; //$annots .= ' /IT '; //$annots .= ' /ExData '; } $lineendings = array('Square', 'Circle', 'Diamond', 'OpenArrow', 'ClosedArrow', 'None', 'Butt', 'ROpenArrow', 'RClosedArrow', 'Slash'); // Annotation types switch (strtolower($pl['opt']['subtype'])) { case 'text': { if (isset($pl['opt']['open'])) { $annots .= ' /Open '. (strtolower($pl['opt']['open']) == 'true' ? 'true' : 'false'); } $iconsapp = array('Comment', 'Help', 'Insert', 'Key', 'NewParagraph', 'Note', 'Paragraph'); if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) { $annots .= ' /Name /'.$pl['opt']['name']; } else { $annots .= ' /Name /Note'; } $statemodels = array('Marked', 'Review'); if (isset($pl['opt']['statemodel']) AND in_array($pl['opt']['statemodel'], $statemodels)) { $annots .= ' /StateModel /'.$pl['opt']['statemodel']; } else { $pl['opt']['statemodel'] = 'Marked'; $annots .= ' /StateModel /'.$pl['opt']['statemodel']; } if ($pl['opt']['statemodel'] == 'Marked') { $states = array('Accepted', 'Unmarked'); } else { $states = array('Accepted', 'Rejected', 'Cancelled', 'Completed', 'None'); } if (isset($pl['opt']['state']) AND in_array($pl['opt']['state'], $states)) { $annots .= ' /State /'.$pl['opt']['state']; } else { if ($pl['opt']['statemodel'] == 'Marked') { $annots .= ' /State /Unmarked'; } else { $annots .= ' /State /None'; } } break; } case 'link': { if(is_string($pl['txt'])) { // external URI link $annots .= ' /A <</S /URI /URI '.$this->_datastring($this->unhtmlentities($pl['txt']), $annot_obj_id).'>>'; } else { // internal link $l = $this->links[$pl['txt']]; $annots .= sprintf(' /Dest [%u 0 R /XYZ 0 %.2F null]', $this->page_obj_id[($l[0])], ($this->pagedim[$l[0]]['h'] - ($l[1] * $this->k))); } $hmodes = array('N', 'I', 'O', 'P'); if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmodes)) { $annots .= ' /H /'.$pl['opt']['h']; } else { $annots .= ' /H /I'; } //$annots .= ' /PA '; //$annots .= ' /Quadpoints '; break; } case 'freetext': { if (isset($pl['opt']['da']) AND !empty($pl['opt']['da'])) { $annots .= ' /DA ('.$pl['opt']['da'].')'; } if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) { $annots .= ' /Q '.intval($pl['opt']['q']); } if (isset($pl['opt']['rc'])) { $annots .= ' /RC '.$this->_textstring($pl['opt']['rc'], $annot_obj_id); } if (isset($pl['opt']['ds'])) { $annots .= ' /DS '.$this->_textstring($pl['opt']['ds'], $annot_obj_id); } if (isset($pl['opt']['cl']) AND is_array($pl['opt']['cl'])) { $annots .= ' /CL ['; foreach ($pl['opt']['cl'] as $cl) { $annots .= sprintf('%.4F ', $cl * $this->k); } $annots .= ']'; } $tfit = array('FreeText', 'FreeTextCallout', 'FreeTextTypeWriter'); if (isset($pl['opt']['it']) AND in_array($pl['opt']['it'], $tfit)) { $annots .= ' /IT /'.$pl['opt']['it']; } if (isset($pl['opt']['rd']) AND is_array($pl['opt']['rd'])) { $l = $pl['opt']['rd'][0] * $this->k; $r = $pl['opt']['rd'][1] * $this->k; $t = $pl['opt']['rd'][2] * $this->k; $b = $pl['opt']['rd'][3] * $this->k; $annots .= ' /RD ['.sprintf('%.2F %.2F %.2F %.2F', $l, $r, $t, $b).']'; } if (isset($pl['opt']['le']) AND in_array($pl['opt']['le'], $lineendings)) { $annots .= ' /LE /'.$pl['opt']['le']; } break; } case 'line': { break; } case 'square': { break; } case 'circle': { break; } case 'polygon': { break; } case 'polyline': { break; } case 'highlight': { break; } case 'underline': { break; } case 'squiggly': { break; } case 'strikeout': { break; } case 'stamp': { break; } case 'caret': { break; } case 'ink': { break; } case 'popup': { break; } case 'fileattachment': { if (!isset($pl['opt']['fs'])) { break; } $filename = basename($pl['opt']['fs']); if (isset($this->embeddedfiles[$filename]['n'])) { $annots .= ' /FS <</Type /Filespec /F '.$this->_datastring($filename, $annot_obj_id).' /EF <</F '.$this->embeddedfiles[$filename]['n'].' 0 R>> >>'; $iconsapp = array('Graph', 'Paperclip', 'PushPin', 'Tag'); if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) { $annots .= ' /Name /'.$pl['opt']['name']; } else { $annots .= ' /Name /PushPin'; } } break; } case 'sound': { if (!isset($pl['opt']['fs'])) { break; } $filename = basename($pl['opt']['fs']); if (isset($this->embeddedfiles[$filename]['n'])) { // ... TO BE COMPLETED ... // /R /C /B /E /CO /CP $annots .= ' /Sound <</Type /Filespec /F '.$this->_datastring($filename, $annot_obj_id).' /EF <</F '.$this->embeddedfiles[$filename]['n'].' 0 R>> >>'; $iconsapp = array('Speaker', 'Mic'); if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) { $annots .= ' /Name /'.$pl['opt']['name']; } else { $annots .= ' /Name /Speaker'; } } break; } case 'movie': { break; } case 'widget': { $hmode = array('N', 'I', 'O', 'P', 'T'); if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmode)) { $annots .= ' /H /'.$pl['opt']['h']; } if (isset($pl['opt']['mk']) AND (is_array($pl['opt']['mk'])) AND !empty($pl['opt']['mk'])) { $annots .= ' /MK <<'; if (isset($pl['opt']['mk']['r'])) { $annots .= ' /R '.$pl['opt']['mk']['r']; } if (isset($pl['opt']['mk']['bc']) AND (is_array($pl['opt']['mk']['bc']))) { $annots .= ' /BC ['; foreach($pl['opt']['mk']['bc'] AS $col) { $col = intval($col); $color = $col <= 0 ? 0 : ($col >= 255 ? 1 : $col / 255); $annots .= sprintf(' %.2F', $color); } $annots .= ']'; } if (isset($pl['opt']['mk']['bg']) AND (is_array($pl['opt']['mk']['bg']))) { $annots .= ' /BG ['; foreach($pl['opt']['mk']['bg'] AS $col) { $col = intval($col); $color = $col <= 0 ? 0 : ($col >= 255 ? 1 : $col / 255); $annots .= sprintf(' %.2F', $color); } $annots .= ']'; } if (isset($pl['opt']['mk']['ca'])) { $annots .= ' /CA '.$pl['opt']['mk']['ca']; } if (isset($pl['opt']['mk']['rc'])) { $annots .= ' /RC '.$pl['opt']['mk']['rc']; } if (isset($pl['opt']['mk']['ac'])) { $annots .= ' /AC '.$pl['opt']['mk']['ac']; } if (isset($pl['opt']['mk']['i'])) { $info = $this->getImageBuffer($pl['opt']['mk']['i']); if ($info !== false) { $annots .= ' /I '.$info['n'].' 0 R'; } } if (isset($pl['opt']['mk']['ri'])) { $info = $this->getImageBuffer($pl['opt']['mk']['ri']); if ($info !== false) { $annots .= ' /RI '.$info['n'].' 0 R'; } } if (isset($pl['opt']['mk']['ix'])) { $info = $this->getImageBuffer($pl['opt']['mk']['ix']); if ($info !== false) { $annots .= ' /IX '.$info['n'].' 0 R'; } } if (isset($pl['opt']['mk']['if']) AND (is_array($pl['opt']['mk']['if'])) AND !empty($pl['opt']['mk']['if'])) { $annots .= ' /IF <<'; $if_sw = array('A', 'B', 'S', 'N'); if (isset($pl['opt']['mk']['if']['sw']) AND in_array($pl['opt']['mk']['if']['sw'], $if_sw)) { $annots .= ' /SW /'.$pl['opt']['mk']['if']['sw']; } $if_s = array('A', 'P'); if (isset($pl['opt']['mk']['if']['s']) AND in_array($pl['opt']['mk']['if']['s'], $if_s)) { $annots .= ' /S /'.$pl['opt']['mk']['if']['s']; } if (isset($pl['opt']['mk']['if']['a']) AND (is_array($pl['opt']['mk']['if']['a'])) AND !empty($pl['opt']['mk']['if']['a'])) { $annots .= sprintf(' /A [%.2F %.2F]', $pl['opt']['mk']['if']['a'][0], $pl['opt']['mk']['if']['a'][1]); } if (isset($pl['opt']['mk']['if']['fb']) AND ($pl['opt']['mk']['if']['fb'])) { $annots .= ' /FB true'; } $annots .= '>>'; } if (isset($pl['opt']['mk']['tp']) AND ($pl['opt']['mk']['tp'] >= 0) AND ($pl['opt']['mk']['tp'] <= 6)) { $annots .= ' /TP '.intval($pl['opt']['mk']['tp']); } else { $annots .= ' /TP 0'; } $annots .= '>>'; } // end MK // --- Entries for field dictionaries --- if (isset($this->radiobutton_groups[$n][$pl['txt']])) { // set parent $annots .= ' /Parent '.$this->radiobutton_groups[$n][$pl['txt']].' 0 R'; } if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) { $annots .= ' /T '.$this->_datastring($pl['opt']['t'], $annot_obj_id); } if (isset($pl['opt']['tu']) AND is_string($pl['opt']['tu'])) { $annots .= ' /TU '.$this->_datastring($pl['opt']['tu'], $annot_obj_id); } if (isset($pl['opt']['tm']) AND is_string($pl['opt']['tm'])) { $annots .= ' /TM '.$this->_datastring($pl['opt']['tm'], $annot_obj_id); } if (isset($pl['opt']['ff'])) { if (is_array($pl['opt']['ff'])) { // array of bit settings $flag = 0; foreach($pl['opt']['ff'] as $val) { $flag += 1 << ($val - 1); } } else { $flag = intval($pl['opt']['ff']); } $annots .= ' /Ff '.$flag; } if (isset($pl['opt']['maxlen'])) { $annots .= ' /MaxLen '.intval($pl['opt']['maxlen']); } if (isset($pl['opt']['v'])) { $annots .= ' /V'; if (is_array($pl['opt']['v'])) { foreach ($pl['opt']['v'] AS $optval) { if (is_float($optval)) { $optval = sprintf('%.2F', $optval); } $annots .= ' '.$optval; } } else { $annots .= ' '.$this->_textstring($pl['opt']['v'], $annot_obj_id); } } if (isset($pl['opt']['dv'])) { $annots .= ' /DV'; if (is_array($pl['opt']['dv'])) { foreach ($pl['opt']['dv'] AS $optval) { if (is_float($optval)) { $optval = sprintf('%.2F', $optval); } $annots .= ' '.$optval; } } else { $annots .= ' '.$this->_textstring($pl['opt']['dv'], $annot_obj_id); } } if (isset($pl['opt']['rv'])) { $annots .= ' /RV'; if (is_array($pl['opt']['rv'])) { foreach ($pl['opt']['rv'] AS $optval) { if (is_float($optval)) { $optval = sprintf('%.2F', $optval); } $annots .= ' '.$optval; } } else { $annots .= ' '.$this->_textstring($pl['opt']['rv'], $annot_obj_id); } } if (isset($pl['opt']['a']) AND !empty($pl['opt']['a'])) { $annots .= ' /A << '.$pl['opt']['a'].' >>'; } if (isset($pl['opt']['aa']) AND !empty($pl['opt']['aa'])) { $annots .= ' /AA << '.$pl['opt']['aa'].' >>'; } if (isset($pl['opt']['da']) AND !empty($pl['opt']['da'])) { $annots .= ' /DA ('.$pl['opt']['da'].')'; } if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) { $annots .= ' /Q '.intval($pl['opt']['q']); } if (isset($pl['opt']['opt']) AND (is_array($pl['opt']['opt'])) AND !empty($pl['opt']['opt'])) { $annots .= ' /Opt ['; foreach($pl['opt']['opt'] AS $copt) { if (is_array($copt)) { $annots .= ' ['.$this->_textstring($copt[0], $annot_obj_id).' '.$this->_textstring($copt[1], $annot_obj_id).']'; } else { $annots .= ' '.$this->_textstring($copt, $annot_obj_id); } } $annots .= ']'; } if (isset($pl['opt']['ti'])) { $annots .= ' /TI '.intval($pl['opt']['ti']); } if (isset($pl['opt']['i']) AND (is_array($pl['opt']['i'])) AND !empty($pl['opt']['i'])) { $annots .= ' /I ['; foreach($pl['opt']['i'] AS $copt) { $annots .= intval($copt).' '; } $annots .= ']'; } break; } case 'screen': { break; } case 'printermark': { break; } case 'trapnet': { break; } case 'watermark': { break; } case '3d': { break; } default: { break; } } $annots .= '>>'; // create new annotation object $this->_out($this->_getobj($annot_obj_id)."\n".$annots."\n".'endobj'); if ($formfield AND !isset($this->radiobutton_groups[$n][$pl['txt']])) { // store reference of form object $this->form_obj_id[] = $annot_obj_id; } } } } // end for each page } /** * Put appearance streams XObject used to define annotation's appearance states * @param int $w annotation width * @param int $h annotation height * @param string $stream appearance stream * @return int object ID * @access protected * @since 4.8.001 (2009-09-09) */ protected function _putAPXObject($w=0, $h=0, $stream='') { $stream = trim($stream); $out = $this->_getobj()."\n"; $this->xobjects['AX'.$this->n] = array('n' => $this->n); $out .= '<<'; $out .= ' /Type /XObject'; $out .= ' /Subtype /Form'; $out .= ' /FormType 1'; if ($this->compress) { $stream = gzcompress($stream); $out .= ' /Filter /FlateDecode'; } $rect = sprintf('%.2F %.2F', $w, $h); $out .= ' /BBox [0 0 '.$rect.']'; $out .= ' /Matrix [1 0 0 1 0 0]'; $out .= ' /Resources <<'; $out .= ' /ProcSet [/PDF /Text]'; $out .= ' /Font <<'; foreach ($this->annotation_fonts as $fontkey => $fontid) { $out .= ' /F'.$fontid.' '.$this->font_obj_ids[$fontkey].' 0 R'; } $out .= ' >>'; $out .= ' >>'; $stream = $this->_getrawstream($stream); $out .= ' /Length '.strlen($stream); $out .= ' >>'; $out .= ' stream'."\n".$stream."\n".'endstream'; $out .= "\n".'endobj'; $this->_out($out); return $this->n; } /** * Get ULONG from string (Big Endian 32-bit unsigned integer). * @param string $str string from where to extract value * @param int $offset point from where to read the data * @return int 32 bit value * @author Nicola Asuni * @access protected * @since 5.2.000 (2010-06-02) */ protected function _getULONG(&$str, &$offset) { $v = unpack('Ni', substr($str, $offset, 4)); $offset += 4; return $v['i']; } /** * Get USHORT from string (Big Endian 16-bit unsigned integer). * @param string $str string from where to extract value * @param int $offset point from where to read the data * @return int 16 bit value * @author Nicola Asuni * @access protected * @since 5.2.000 (2010-06-02) */ protected function _getUSHORT(&$str, &$offset) { $v = unpack('ni', substr($str, $offset, 2)); $offset += 2; return $v['i']; } /** * Get SHORT from string (Big Endian 16-bit signed integer). * @param string $str string from where to extract value * @param int $offset point from where to read the data * @return int 16 bit value * @author Nicola Asuni * @access protected * @since 5.2.000 (2010-06-02) */ protected function _getSHORT(&$str, &$offset) { $v = unpack('si', substr($str, $offset, 2)); $offset += 2; return $v['i']; } /** * Get BYTE from string (8-bit unsigned integer). * @param string $str string from where to extract value * @param int $offset point from where to read the data * @return int 8 bit value * @author Nicola Asuni * @access protected * @since 5.2.000 (2010-06-02) */ protected function _getBYTE(&$str, &$offset) { $v = unpack('Ci', substr($str, $offset, 1)); ++$offset; return $v['i']; } /** * Returns a subset of the TrueType font data without the unused glyphs. * @param string $font TrueType font data * @param array $subsetchars array of used characters (the glyphs to keep) * @return string a subset of TrueType font data without the unused glyphs * @author Nicola Asuni * @access protected * @since 5.2.000 (2010-06-02) */ protected function _getTrueTypeFontSubset($font, $subsetchars) { ksort($subsetchars); $offset = 0; // offset position of the font data if ($this->_getULONG($font, $offset) != 0x10000) { // sfnt version must be 0x00010000 for TrueType version 1.0. return $font; } // get number of tables $numTables = $this->_getUSHORT($font, $offset); // skip searchRange, entrySelector and rangeShift $offset += 6; // tables array $table = array(); // for each table for ($i = 0; $i < $numTables; ++$i) { // get table info $tag = substr($font, $offset, 4); $offset += 4; $table[$tag] = array(); $table[$tag]['checkSum'] = $this->_getULONG($font, $offset); $table[$tag]['offset'] = $this->_getULONG($font, $offset); $table[$tag]['length'] = $this->_getULONG($font, $offset); } // check magicNumber $offset = $table['head']['offset'] + 12; if ($this->_getULONG($font, $offset) != 0x5F0F3CF5) { // magicNumber must be 0x5F0F3CF5 return $font; } // get offset mode (indexToLocFormat : 0 = short, 1 = long) $offset = $table['head']['offset'] + 50; $short_offset = ($this->_getSHORT($font, $offset) == 0); // get the offsets to the locations of the glyphs in the font, relative to the beginning of the glyphData table $indexToLoc = array(); $offset = $table['loca']['offset']; if ($short_offset) { // short version $n = $table['loca']['length'] / 2; // numGlyphs + 1 for ($i = 0; $i < $n; ++$i) { $indexToLoc[$i] = $this->_getUSHORT($font, $offset) * 2; } } else { // long version $n = $table['loca']['length'] / 4; // numGlyphs + 1 for ($i = 0; $i < $n; ++$i) { $indexToLoc[$i] = $this->_getULONG($font, $offset); } } // get glyphs indexes of chars from cmap table $subsetglyphs = array(); // glyph IDs on key $subsetglyphs[0] = true; // character codes that do not correspond to any glyph in the font should be mapped to glyph index 0 $offset = $table['cmap']['offset'] + 2; $numEncodingTables = $this->_getUSHORT($font, $offset); $encodingTables = array(); for ($i = 0; $i < $numEncodingTables; ++$i) { $encodingTables[$i]['platformID'] = $this->_getUSHORT($font, $offset); $encodingTables[$i]['encodingID'] = $this->_getUSHORT($font, $offset); $encodingTables[$i]['offset'] = $this->_getULONG($font, $offset); } foreach ($encodingTables as $enctable) { if (($enctable['platformID'] == 3) AND ($enctable['encodingID'] == 0)) { $modesymbol = true; } else { $modesymbol = false; } $offset = $table['cmap']['offset'] + $enctable['offset']; $format = $this->_getUSHORT($font, $offset); switch ($format) { case 0: { // Format 0: Byte encoding table $offset += 4; // skip length and version/language for ($k = 0; $k < 256; ++$k) { if (isset($subsetchars[$k])) { $g = $this->_getBYTE($font, $offset); $subsetglyphs[$g] = $k; } else { ++$offset; } } break; } case 2: { // Format 2: High-byte mapping through table $offset += 4; // skip length and version // to be implemented ... break; } case 4: { // Format 4: Segment mapping to delta values $length = $this->_getUSHORT($font, $offset); $offset += 2; // skip version/language $segCount = ($this->_getUSHORT($font, $offset) / 2); $offset += 6; // skip searchRange, entrySelector, rangeShift $endCount = array(); // array of end character codes for each segment for ($k = 0; $k < $segCount; ++$k) { $endCount[$k] = $this->_getUSHORT($font, $offset); } $offset += 2; // skip reservedPad $startCount = array(); // array of start character codes for each segment for ($k = 0; $k < $segCount; ++$k) { $startCount[$k] = $this->_getUSHORT($font, $offset); } $idDelta = array(); // delta for all character codes in segment for ($k = 0; $k < $segCount; ++$k) { $idDelta[$k] = $this->_getUSHORT($font, $offset); } $idRangeOffset = array(); // Offsets into glyphIdArray or 0 for ($k = 0; $k < $segCount; ++$k) { $idRangeOffset[$k] = $this->_getUSHORT($font, $offset); } $gidlen = ($length / 2) - 8 - (4 * $segCount); $glyphIdArray = array(); // glyph index array for ($k = 0; $k < $gidlen; ++$k) { $glyphIdArray[$k] = $this->_getUSHORT($font, $offset); } for ($k = 0; $k < $segCount; ++$k) { for ($c = $startCount[$k]; $c <= $endCount[$k]; ++$c) { if (isset($subsetchars[$c])) { if ($idRangeOffset[$k] == 0) { $g = $c; } else { $gid = (($idRangeOffset[$k] / 2) + ($c - $startCount[$k]) - ($segCount - $k)); $g = $glyphIdArray[$gid]; } $g += ($idDelta[$k] - 65536); if ($g < 0) { $g = 0; } $subsetglyphs[$g] = $c; } } } break; } case 6: { // Format 6: Trimmed table mapping $offset += 4; // skip length and version/language $firstCode = $this->_getUSHORT($font, $offset); $entryCount = $this->_getUSHORT($font, $offset); for ($k = 0; $k < $entryCount; ++$k) { $c = ($k + $firstCode); if (isset($subsetchars[$c])) { $g = $this->_getUSHORT($font, $offset); $subsetglyphs[$g] = $c; } else { $offset += 2; } } break; } case 8: { // Format 8: Mixed 16-bit and 32-bit coverage $offset += 10; // skip length and version // to be implemented ... break; } case 10: { // Format 10: Trimmed array $offset += 10; // skip length and version/language $startCharCode = $this->_getULONG($font, $offset); $numChars = $this->_getULONG($font, $offset); for ($k = 0; $k < $numChars; ++$k) { $c = ($k + $startCharCode); if (isset($subsetchars[$c])) { $g = $this->_getUSHORT($font, $offset); $subsetglyphs[$g] = $c; } else { $offset += 2; } } break; } case 12: { // Format 12: Segmented coverage $offset += 10; // skip length and version/language $nGroups = $this->_getULONG($font, $offset); for ($k = 0; $k < $nGroups; ++$k) { $startCharCode = $this->_getULONG($font, $offset); $endCharCode = $this->_getULONG($font, $offset); $startGlyphCode = $this->_getULONG($font, $offset); for ($c = $startCharCode; $c <= $endCharCode; ++$c) { if (isset($subsetchars[$c])) { $subsetglyphs[$startGlyphCode] = $c; } ++$startGlyphCode; } } break; } } } // sort glyphs by key ksort($subsetglyphs); // add composite glyps to $subsetglyphs and remove missing glyphs foreach ($subsetglyphs as $key => $val) { if (isset($indexToLoc[$key])) { $offset = $table['glyf']['offset'] + $indexToLoc[$key]; $numberOfContours = $this->_getSHORT($font, $offset); if ($numberOfContours < 0) { // composite glyph $offset += 8; // skip xMin, yMin, xMax, yMax do { $flags = $this->_getUSHORT($font, $offset); $glyphIndex = $this->_getUSHORT($font, $offset); if (!isset($subsetglyphs[$glyphIndex]) AND isset($indexToLoc[$glyphIndex])) { // add missing glyphs $subsetglyphs[$glyphIndex] = true; } // skip some bytes by case if ($flags & 1) { $offset += 4; } else { $offset += 2; } if ($flags & 8) { $offset += 2; } elseif ($flags & 64) { $offset += 4; } elseif ($flags & 128) { $offset += 8; } } while ($flags & 32); } } else { unset($subsetglyphs[$key]); } } // build new glyf table with only used glyphs $glyf = ''; $glyfSize = 0; // create new empty indexToLoc table $newIndexToLoc = array_fill(0, count($indexToLoc), 0); $goffset = 0; foreach ($subsetglyphs as $glyphID => $char) { if (isset($indexToLoc[$glyphID]) AND isset($indexToLoc[($glyphID + 1)])) { $start = $indexToLoc[$glyphID]; $length = ($indexToLoc[($glyphID + 1)] - $start); $glyf .= substr($font, ($table['glyf']['offset'] + $start), $length); $newIndexToLoc[$glyphID] = $goffset; $goffset += $length; } } // build new loca table $loca = ''; if ($short_offset) { foreach ($newIndexToLoc as $glyphID => $offset) { $loca .= pack('n', ($offset / 2)); } } else { foreach ($newIndexToLoc as $glyphID => $offset) { $loca .= pack('N', $offset); } } // array of table names to preserve (loca and glyf tables will be added later) //$table_names = array ('cmap', 'head', 'hhea', 'hmtx', 'maxp', 'name', 'OS/2', 'post', 'cvt ', 'fpgm', 'prep'); // the cmap table is not needed and shall not be present, since the mapping from character codes to glyph descriptions is provided separately $table_names = array ('head', 'hhea', 'hmtx', 'maxp', 'cvt ', 'fpgm', 'prep'); // minimum required table names // get the tables to preserve $offset = 12; foreach ($table as $tag => $val) { if (in_array($tag, $table_names)) { $table[$tag]['data'] = substr($font, $table[$tag]['offset'], $table[$tag]['length']); if ($tag == 'head') { // set the checkSumAdjustment to 0 $table[$tag]['data'] = substr($table[$tag]['data'], 0, 8)."\x0\x0\x0\x0".substr($table[$tag]['data'], 12); } $pad = 4 - ($table[$tag]['length'] % 4); if ($pad != 4) { // the length of a table must be a multiple of four bytes $table[$tag]['length'] += $pad; $table[$tag]['data'] .= str_repeat("\x0", $pad); } $table[$tag]['offset'] = $offset; $offset += $table[$tag]['length']; // check sum is not changed (so keep the following line commented) //$table[$tag]['checkSum'] = $this->_getTTFtableChecksum($table[$tag]['data'], $table[$tag]['length']); } else { unset($table[$tag]); } } // add loca $table['loca']['data'] = $loca; $table['loca']['length'] = strlen($loca); $pad = 4 - ($table['loca']['length'] % 4); if ($pad != 4) { // the length of a table must be a multiple of four bytes $table['loca']['length'] += $pad; $table['loca']['data'] .= str_repeat("\x0", $pad); } $table['loca']['offset'] = $offset; $table['loca']['checkSum'] = $this->_getTTFtableChecksum($table['loca']['data'], $table['loca']['length']); $offset += $table['loca']['length']; // add glyf $table['glyf']['data'] = $glyf; $table['glyf']['length'] = strlen($glyf); $pad = 4 - ($table['glyf']['length'] % 4); if ($pad != 4) { // the length of a table must be a multiple of four bytes $table['glyf']['length'] += $pad; $table['glyf']['data'] .= str_repeat("\x0", $pad); } $table['glyf']['offset'] = $offset; $table['glyf']['checkSum'] = $this->_getTTFtableChecksum($table['glyf']['data'], $table['glyf']['length']); // rebuild font $font = ''; $font .= pack('N', 0x10000); // sfnt version $numTables = count($table); $font .= pack('n', $numTables); // numTables $entrySelector = floor(log($numTables, 2)); $searchRange = pow(2, $entrySelector) * 16; $rangeShift = ($numTables * 16) - $searchRange; $font .= pack('n', $searchRange); // searchRange $font .= pack('n', $entrySelector); // entrySelector $font .= pack('n', $rangeShift); // rangeShift $offset = ($numTables * 16); foreach ($table as $tag => $data) { $font .= $tag; // tag $font .= pack('N', $data['checkSum']); // checkSum $font .= pack('N', ($data['offset'] + $offset)); // offset $font .= pack('N', $data['length']); // length } foreach ($table as $data) { $font .= $data['data']; } // set checkSumAdjustment on head table $checkSumAdjustment = 0xB1B0AFBA - $this->_getTTFtableChecksum($font, strlen($font)); $font = substr($font, 0, $table['head']['offset'] + 8).pack('N', $checkSumAdjustment).substr($font, $table['head']['offset'] + 12); return $font; } /** * Returs the checksum of a TTF table. * @param string $table table to check * @param int $length lenght of table in bytes * @return int checksum * @author Nicola Asuni * @access protected * @since 5.2.000 (2010-06-02) */ protected function _getTTFtableChecksum($table, $length) { $sum = 0; $tlen = ($length / 4); $offset = 0; for ($i = 0; $i < $tlen; ++$i) { $v = unpack('Ni', substr($table, $offset, 4)); $sum += $v['i']; $offset += 4; } $sum = unpack('Ni', pack('N', $sum)); return $sum['i']; } /** * Outputs font widths * @param array $font font data * @param int $cidoffset offset for CID values * @return PDF command string for font widths * @author Nicola Asuni * @access protected * @since 4.4.000 (2008-12-07) */ protected function _putfontwidths($font, $cidoffset=0) { ksort($font['cw']); $rangeid = 0; $range = array(); $prevcid = -2; $prevwidth = -1; $interval = false; // for each character foreach ($font['cw'] as $cid => $width) { $cid -= $cidoffset; if ($font['subset'] AND ($cid > 255) AND (!isset($font['subsetchars'][$cid]))) { // ignore the unused characters (font subsetting) continue; } if ($width != $font['dw']) { if ($cid == ($prevcid + 1)) { // consecutive CID if ($width == $prevwidth) { if ($width == $range[$rangeid][0]) { $range[$rangeid][] = $width; } else { array_pop($range[$rangeid]); // new range $rangeid = $prevcid; $range[$rangeid] = array(); $range[$rangeid][] = $prevwidth; $range[$rangeid][] = $width; } $interval = true; $range[$rangeid]['interval'] = true; } else { if ($interval) { // new range $rangeid = $cid; $range[$rangeid] = array(); $range[$rangeid][] = $width; } else { $range[$rangeid][] = $width; } $interval = false; } } else { // new range $rangeid = $cid; $range[$rangeid] = array(); $range[$rangeid][] = $width; $interval = false; } $prevcid = $cid; $prevwidth = $width; } } // optimize ranges $prevk = -1; $nextk = -1; $prevint = false; foreach ($range as $k => $ws) { $cws = count($ws); if (($k == $nextk) AND (!$prevint) AND ((!isset($ws['interval'])) OR ($cws < 4))) { if (isset($range[$k]['interval'])) { unset($range[$k]['interval']); } $range[$prevk] = array_merge($range[$prevk], $range[$k]); unset($range[$k]); } else { $prevk = $k; } $nextk = $k + $cws; if (isset($ws['interval'])) { if ($cws > 3) { $prevint = true; } else { $prevint = false; } unset($range[$k]['interval']); --$nextk; } else { $prevint = false; } } // output data $w = ''; foreach ($range as $k => $ws) { if (count(array_count_values($ws)) == 1) { // interval mode is more compact $w .= ' '.$k.' '.($k + count($ws) - 1).' '.$ws[0]; } else { // range mode $w .= ' '.$k.' [ '.implode(' ', $ws).' ]'; } } return '/W ['.$w.' ]'; } /** * Output fonts. * @author Nicola Asuni * @access protected */ protected function _putfonts() { $nf = $this->n; foreach ($this->diffs as $diff) { //Encodings $this->_newobj(); $this->_out('<< /Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.'] >>'."\n".'endobj'); } $mqr = $this->get_mqr(); $this->set_mqr(false); foreach ($this->FontFiles as $file => $info) { // search and get font file to embedd $fontdir = $info['fontdir']; $file = strtolower($file); $fontfile = ''; // search files on various directories if (($fontdir !== false) AND file_exists($fontdir.$file)) { $fontfile = $fontdir.$file; } elseif (file_exists($this->_getfontpath().$file)) { $fontfile = $this->_getfontpath().$file; } elseif (file_exists($file)) { $fontfile = $file; } if (!$this->empty_string($fontfile)) { $font = file_get_contents($fontfile); $compressed = (substr($file, -2) == '.z'); if ((!$compressed) AND (isset($info['length2']))) { $header = (ord($font{0}) == 128); if ($header) { //Strip first binary header $font = substr($font, 6); } if ($header AND (ord($font{$info['length1']}) == 128)) { //Strip second binary header $font = substr($font, 0, $info['length1']).substr($font, ($info['length1'] + 6)); } } elseif ($info['subset'] AND ((!$compressed) OR ($compressed AND function_exists('gzcompress')))) { if ($compressed) { // uncompress font $font = gzuncompress($font); } // merge subset characters $subsetchars = array(); // used chars foreach ($info['fontkeys'] as $fontkey) { $fontinfo = $this->getFontBuffer($fontkey); $subsetchars += $fontinfo['subsetchars']; } $font = $this->_getTrueTypeFontSubset($font, $subsetchars); if ($compressed) { // recompress font $font = gzcompress($font); } } $this->_newobj(); $this->FontFiles[$file]['n'] = $this->n; $stream = $this->_getrawstream($font); $out = '<< /Length '.strlen($stream); if ($compressed) { $out .= ' /Filter /FlateDecode'; } $out .= ' /Length1 '.$info['length1']; if (isset($info['length2'])) { $out .= ' /Length2 '.$info['length2'].' /Length3 0'; } $out .= ' >>'; $out .= ' stream'."\n".$stream."\n".'endstream'; $out .= "\n".'endobj'; $this->_out($out); } } $this->set_mqr($mqr); foreach ($this->fontkeys as $k) { //Font objects $font = $this->getFontBuffer($k); $type = $font['type']; $name = $font['name']; if ($type == 'core') { // standard core font $out = $this->_getobj($this->font_obj_ids[$k])."\n"; $out .= '<</Type /Font'; $out .= ' /Subtype /Type1'; $out .= ' /BaseFont /'.$name; $out .= ' /Name /F'.$font['i']; if ((strtolower($name) != 'symbol') AND (strtolower($name) != 'zapfdingbats')) { $out .= ' /Encoding /WinAnsiEncoding'; } if ($k == 'helvetica') { // add default font for annotations $this->annotation_fonts[$k] = $font['i']; } $out .= ' >>'; $out .= "\n".'endobj'; $this->_out($out); } elseif (($type == 'Type1') OR ($type == 'TrueType')) { // additional Type1 or TrueType font $out = $this->_getobj($this->font_obj_ids[$k])."\n"; $out .= '<</Type /Font'; $out .= ' /Subtype /'.$type; $out .= ' /BaseFont /'.$name; $out .= ' /Name /F'.$font['i']; $out .= ' /FirstChar 32 /LastChar 255'; $out .= ' /Widths '.($this->n + 1).' 0 R'; $out .= ' /FontDescriptor '.($this->n + 2).' 0 R'; if ($font['enc']) { if (isset($font['diff'])) { $out .= ' /Encoding '.($nf + $font['diff']).' 0 R'; } else { $out .= ' /Encoding /WinAnsiEncoding'; } } $out .= ' >>'; $out .= "\n".'endobj'; $this->_out($out); // Widths $this->_newobj(); $cw = &$font['cw']; $s = '['; for ($i = 32; $i < 256; ++$i) { $s .= $cw[$i].' '; } $s .= ']'; $s .= "\n".'endobj'; $this->_out($s); //Descriptor $this->_newobj(); $s = '<</Type /FontDescriptor /FontName /'.$name; foreach ($font['desc'] as $fdk => $fdv) { if(is_float($fdv)) { $fdv = sprintf('%.3F', $fdv); } $s .= ' /'.$fdk.' '.$fdv.''; } if (!$this->empty_string($font['file'])) { $s .= ' /FontFile'.($type == 'Type1' ? '' : '2').' '.$this->FontFiles[$font['file']]['n'].' 0 R'; } $s .= '>>'; $s .= "\n".'endobj'; $this->_out($s); } else { // additional types $mtd = '_put'.strtolower($type); if (!method_exists($this, $mtd)) { $this->Error('Unsupported font type: '.$type); } $this->$mtd($font); } } } /** * Adds unicode fonts.<br> * Based on PDF Reference 1.3 (section 5) * @param array $font font data * @access protected * @author Nicola Asuni * @since 1.52.0.TC005 (2005-01-05) */ protected function _puttruetypeunicode($font) { $fontname = ''; if ($font['subset']) { // change name for font subsetting $subtag = sprintf('%06u', $font['i']); $subtag = strtr($subtag, '0123456789', 'ABCDEFGHIJ'); $fontname .= $subtag.'+'; } $fontname .= $font['name']; // Type0 Font // A composite font composed of other fonts, organized hierarchically $out = $this->_getobj($this->font_obj_ids[$font['fontkey']])."\n"; $out .= '<< /Type /Font'; $out .= ' /Subtype /Type0'; $out .= ' /BaseFont /'.$fontname; $out .= ' /Name /F'.$font['i']; $out .= ' /Encoding /'.$font['enc']; $out .= ' /ToUnicode '.($this->n + 1).' 0 R'; $out .= ' /DescendantFonts ['.($this->n + 2).' 0 R]'; $out .= ' >>'; $out .= "\n".'endobj'; $this->_out($out); // ToUnicode map for Identity-H $stream = "/CIDInit /ProcSet findresource begin\n"; $stream .= "12 dict begin\n"; $stream .= "begincmap\n"; $stream .= "/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n"; $stream .= "/CMapName /Adobe-Identity-UCS def\n"; $stream .= "/CMapType 2 def\n"; $stream .= "/WMode 0 def\n"; $stream .= "1 begincodespacerange\n"; $stream .= "<0000> <FFFF>\n"; $stream .= "endcodespacerange\n"; $stream .= "100 beginbfrange\n"; $stream .= "<0000> <00ff> <0000>\n"; $stream .= "<0100> <01ff> <0100>\n"; $stream .= "<0200> <02ff> <0200>\n"; $stream .= "<0300> <03ff> <0300>\n"; $stream .= "<0400> <04ff> <0400>\n"; $stream .= "<0500> <05ff> <0500>\n"; $stream .= "<0600> <06ff> <0600>\n"; $stream .= "<0700> <07ff> <0700>\n"; $stream .= "<0800> <08ff> <0800>\n"; $stream .= "<0900> <09ff> <0900>\n"; $stream .= "<0a00> <0aff> <0a00>\n"; $stream .= "<0b00> <0bff> <0b00>\n"; $stream .= "<0c00> <0cff> <0c00>\n"; $stream .= "<0d00> <0dff> <0d00>\n"; $stream .= "<0e00> <0eff> <0e00>\n"; $stream .= "<0f00> <0fff> <0f00>\n"; $stream .= "<1000> <10ff> <1000>\n"; $stream .= "<1100> <11ff> <1100>\n"; $stream .= "<1200> <12ff> <1200>\n"; $stream .= "<1300> <13ff> <1300>\n"; $stream .= "<1400> <14ff> <1400>\n"; $stream .= "<1500> <15ff> <1500>\n"; $stream .= "<1600> <16ff> <1600>\n"; $stream .= "<1700> <17ff> <1700>\n"; $stream .= "<1800> <18ff> <1800>\n"; $stream .= "<1900> <19ff> <1900>\n"; $stream .= "<1a00> <1aff> <1a00>\n"; $stream .= "<1b00> <1bff> <1b00>\n"; $stream .= "<1c00> <1cff> <1c00>\n"; $stream .= "<1d00> <1dff> <1d00>\n"; $stream .= "<1e00> <1eff> <1e00>\n"; $stream .= "<1f00> <1fff> <1f00>\n"; $stream .= "<2000> <20ff> <2000>\n"; $stream .= "<2100> <21ff> <2100>\n"; $stream .= "<2200> <22ff> <2200>\n"; $stream .= "<2300> <23ff> <2300>\n"; $stream .= "<2400> <24ff> <2400>\n"; $stream .= "<2500> <25ff> <2500>\n"; $stream .= "<2600> <26ff> <2600>\n"; $stream .= "<2700> <27ff> <2700>\n"; $stream .= "<2800> <28ff> <2800>\n"; $stream .= "<2900> <29ff> <2900>\n"; $stream .= "<2a00> <2aff> <2a00>\n"; $stream .= "<2b00> <2bff> <2b00>\n"; $stream .= "<2c00> <2cff> <2c00>\n"; $stream .= "<2d00> <2dff> <2d00>\n"; $stream .= "<2e00> <2eff> <2e00>\n"; $stream .= "<2f00> <2fff> <2f00>\n"; $stream .= "<3000> <30ff> <3000>\n"; $stream .= "<3100> <31ff> <3100>\n"; $stream .= "<3200> <32ff> <3200>\n"; $stream .= "<3300> <33ff> <3300>\n"; $stream .= "<3400> <34ff> <3400>\n"; $stream .= "<3500> <35ff> <3500>\n"; $stream .= "<3600> <36ff> <3600>\n"; $stream .= "<3700> <37ff> <3700>\n"; $stream .= "<3800> <38ff> <3800>\n"; $stream .= "<3900> <39ff> <3900>\n"; $stream .= "<3a00> <3aff> <3a00>\n"; $stream .= "<3b00> <3bff> <3b00>\n"; $stream .= "<3c00> <3cff> <3c00>\n"; $stream .= "<3d00> <3dff> <3d00>\n"; $stream .= "<3e00> <3eff> <3e00>\n"; $stream .= "<3f00> <3fff> <3f00>\n"; $stream .= "<4000> <40ff> <4000>\n"; $stream .= "<4100> <41ff> <4100>\n"; $stream .= "<4200> <42ff> <4200>\n"; $stream .= "<4300> <43ff> <4300>\n"; $stream .= "<4400> <44ff> <4400>\n"; $stream .= "<4500> <45ff> <4500>\n"; $stream .= "<4600> <46ff> <4600>\n"; $stream .= "<4700> <47ff> <4700>\n"; $stream .= "<4800> <48ff> <4800>\n"; $stream .= "<4900> <49ff> <4900>\n"; $stream .= "<4a00> <4aff> <4a00>\n"; $stream .= "<4b00> <4bff> <4b00>\n"; $stream .= "<4c00> <4cff> <4c00>\n"; $stream .= "<4d00> <4dff> <4d00>\n"; $stream .= "<4e00> <4eff> <4e00>\n"; $stream .= "<4f00> <4fff> <4f00>\n"; $stream .= "<5000> <50ff> <5000>\n"; $stream .= "<5100> <51ff> <5100>\n"; $stream .= "<5200> <52ff> <5200>\n"; $stream .= "<5300> <53ff> <5300>\n"; $stream .= "<5400> <54ff> <5400>\n"; $stream .= "<5500> <55ff> <5500>\n"; $stream .= "<5600> <56ff> <5600>\n"; $stream .= "<5700> <57ff> <5700>\n"; $stream .= "<5800> <58ff> <5800>\n"; $stream .= "<5900> <59ff> <5900>\n"; $stream .= "<5a00> <5aff> <5a00>\n"; $stream .= "<5b00> <5bff> <5b00>\n"; $stream .= "<5c00> <5cff> <5c00>\n"; $stream .= "<5d00> <5dff> <5d00>\n"; $stream .= "<5e00> <5eff> <5e00>\n"; $stream .= "<5f00> <5fff> <5f00>\n"; $stream .= "<6000> <60ff> <6000>\n"; $stream .= "<6100> <61ff> <6100>\n"; $stream .= "<6200> <62ff> <6200>\n"; $stream .= "<6300> <63ff> <6300>\n"; $stream .= "endbfrange\n"; $stream .= "100 beginbfrange\n"; $stream .= "<6400> <64ff> <6400>\n"; $stream .= "<6500> <65ff> <6500>\n"; $stream .= "<6600> <66ff> <6600>\n"; $stream .= "<6700> <67ff> <6700>\n"; $stream .= "<6800> <68ff> <6800>\n"; $stream .= "<6900> <69ff> <6900>\n"; $stream .= "<6a00> <6aff> <6a00>\n"; $stream .= "<6b00> <6bff> <6b00>\n"; $stream .= "<6c00> <6cff> <6c00>\n"; $stream .= "<6d00> <6dff> <6d00>\n"; $stream .= "<6e00> <6eff> <6e00>\n"; $stream .= "<6f00> <6fff> <6f00>\n"; $stream .= "<7000> <70ff> <7000>\n"; $stream .= "<7100> <71ff> <7100>\n"; $stream .= "<7200> <72ff> <7200>\n"; $stream .= "<7300> <73ff> <7300>\n"; $stream .= "<7400> <74ff> <7400>\n"; $stream .= "<7500> <75ff> <7500>\n"; $stream .= "<7600> <76ff> <7600>\n"; $stream .= "<7700> <77ff> <7700>\n"; $stream .= "<7800> <78ff> <7800>\n"; $stream .= "<7900> <79ff> <7900>\n"; $stream .= "<7a00> <7aff> <7a00>\n"; $stream .= "<7b00> <7bff> <7b00>\n"; $stream .= "<7c00> <7cff> <7c00>\n"; $stream .= "<7d00> <7dff> <7d00>\n"; $stream .= "<7e00> <7eff> <7e00>\n"; $stream .= "<7f00> <7fff> <7f00>\n"; $stream .= "<8000> <80ff> <8000>\n"; $stream .= "<8100> <81ff> <8100>\n"; $stream .= "<8200> <82ff> <8200>\n"; $stream .= "<8300> <83ff> <8300>\n"; $stream .= "<8400> <84ff> <8400>\n"; $stream .= "<8500> <85ff> <8500>\n"; $stream .= "<8600> <86ff> <8600>\n"; $stream .= "<8700> <87ff> <8700>\n"; $stream .= "<8800> <88ff> <8800>\n"; $stream .= "<8900> <89ff> <8900>\n"; $stream .= "<8a00> <8aff> <8a00>\n"; $stream .= "<8b00> <8bff> <8b00>\n"; $stream .= "<8c00> <8cff> <8c00>\n"; $stream .= "<8d00> <8dff> <8d00>\n"; $stream .= "<8e00> <8eff> <8e00>\n"; $stream .= "<8f00> <8fff> <8f00>\n"; $stream .= "<9000> <90ff> <9000>\n"; $stream .= "<9100> <91ff> <9100>\n"; $stream .= "<9200> <92ff> <9200>\n"; $stream .= "<9300> <93ff> <9300>\n"; $stream .= "<9400> <94ff> <9400>\n"; $stream .= "<9500> <95ff> <9500>\n"; $stream .= "<9600> <96ff> <9600>\n"; $stream .= "<9700> <97ff> <9700>\n"; $stream .= "<9800> <98ff> <9800>\n"; $stream .= "<9900> <99ff> <9900>\n"; $stream .= "<9a00> <9aff> <9a00>\n"; $stream .= "<9b00> <9bff> <9b00>\n"; $stream .= "<9c00> <9cff> <9c00>\n"; $stream .= "<9d00> <9dff> <9d00>\n"; $stream .= "<9e00> <9eff> <9e00>\n"; $stream .= "<9f00> <9fff> <9f00>\n"; $stream .= "<a000> <a0ff> <a000>\n"; $stream .= "<a100> <a1ff> <a100>\n"; $stream .= "<a200> <a2ff> <a200>\n"; $stream .= "<a300> <a3ff> <a300>\n"; $stream .= "<a400> <a4ff> <a400>\n"; $stream .= "<a500> <a5ff> <a500>\n"; $stream .= "<a600> <a6ff> <a600>\n"; $stream .= "<a700> <a7ff> <a700>\n"; $stream .= "<a800> <a8ff> <a800>\n"; $stream .= "<a900> <a9ff> <a900>\n"; $stream .= "<aa00> <aaff> <aa00>\n"; $stream .= "<ab00> <abff> <ab00>\n"; $stream .= "<ac00> <acff> <ac00>\n"; $stream .= "<ad00> <adff> <ad00>\n"; $stream .= "<ae00> <aeff> <ae00>\n"; $stream .= "<af00> <afff> <af00>\n"; $stream .= "<b000> <b0ff> <b000>\n"; $stream .= "<b100> <b1ff> <b100>\n"; $stream .= "<b200> <b2ff> <b200>\n"; $stream .= "<b300> <b3ff> <b300>\n"; $stream .= "<b400> <b4ff> <b400>\n"; $stream .= "<b500> <b5ff> <b500>\n"; $stream .= "<b600> <b6ff> <b600>\n"; $stream .= "<b700> <b7ff> <b700>\n"; $stream .= "<b800> <b8ff> <b800>\n"; $stream .= "<b900> <b9ff> <b900>\n"; $stream .= "<ba00> <baff> <ba00>\n"; $stream .= "<bb00> <bbff> <bb00>\n"; $stream .= "<bc00> <bcff> <bc00>\n"; $stream .= "<bd00> <bdff> <bd00>\n"; $stream .= "<be00> <beff> <be00>\n"; $stream .= "<bf00> <bfff> <bf00>\n"; $stream .= "<c000> <c0ff> <c000>\n"; $stream .= "<c100> <c1ff> <c100>\n"; $stream .= "<c200> <c2ff> <c200>\n"; $stream .= "<c300> <c3ff> <c300>\n"; $stream .= "<c400> <c4ff> <c400>\n"; $stream .= "<c500> <c5ff> <c500>\n"; $stream .= "<c600> <c6ff> <c600>\n"; $stream .= "<c700> <c7ff> <c700>\n"; $stream .= "endbfrange\n"; $stream .= "56 beginbfrange\n"; $stream .= "<c800> <c8ff> <c800>\n"; $stream .= "<c900> <c9ff> <c900>\n"; $stream .= "<ca00> <caff> <ca00>\n"; $stream .= "<cb00> <cbff> <cb00>\n"; $stream .= "<cc00> <ccff> <cc00>\n"; $stream .= "<cd00> <cdff> <cd00>\n"; $stream .= "<ce00> <ceff> <ce00>\n"; $stream .= "<cf00> <cfff> <cf00>\n"; $stream .= "<d000> <d0ff> <d000>\n"; $stream .= "<d100> <d1ff> <d100>\n"; $stream .= "<d200> <d2ff> <d200>\n"; $stream .= "<d300> <d3ff> <d300>\n"; $stream .= "<d400> <d4ff> <d400>\n"; $stream .= "<d500> <d5ff> <d500>\n"; $stream .= "<d600> <d6ff> <d600>\n"; $stream .= "<d700> <d7ff> <d700>\n"; $stream .= "<d800> <d8ff> <d800>\n"; $stream .= "<d900> <d9ff> <d900>\n"; $stream .= "<da00> <daff> <da00>\n"; $stream .= "<db00> <dbff> <db00>\n"; $stream .= "<dc00> <dcff> <dc00>\n"; $stream .= "<dd00> <ddff> <dd00>\n"; $stream .= "<de00> <deff> <de00>\n"; $stream .= "<df00> <dfff> <df00>\n"; $stream .= "<e000> <e0ff> <e000>\n"; $stream .= "<e100> <e1ff> <e100>\n"; $stream .= "<e200> <e2ff> <e200>\n"; $stream .= "<e300> <e3ff> <e300>\n"; $stream .= "<e400> <e4ff> <e400>\n"; $stream .= "<e500> <e5ff> <e500>\n"; $stream .= "<e600> <e6ff> <e600>\n"; $stream .= "<e700> <e7ff> <e700>\n"; $stream .= "<e800> <e8ff> <e800>\n"; $stream .= "<e900> <e9ff> <e900>\n"; $stream .= "<ea00> <eaff> <ea00>\n"; $stream .= "<eb00> <ebff> <eb00>\n"; $stream .= "<ec00> <ecff> <ec00>\n"; $stream .= "<ed00> <edff> <ed00>\n"; $stream .= "<ee00> <eeff> <ee00>\n"; $stream .= "<ef00> <efff> <ef00>\n"; $stream .= "<f000> <f0ff> <f000>\n"; $stream .= "<f100> <f1ff> <f100>\n"; $stream .= "<f200> <f2ff> <f200>\n"; $stream .= "<f300> <f3ff> <f300>\n"; $stream .= "<f400> <f4ff> <f400>\n"; $stream .= "<f500> <f5ff> <f500>\n"; $stream .= "<f600> <f6ff> <f600>\n"; $stream .= "<f700> <f7ff> <f700>\n"; $stream .= "<f800> <f8ff> <f800>\n"; $stream .= "<f900> <f9ff> <f900>\n"; $stream .= "<fa00> <faff> <fa00>\n"; $stream .= "<fb00> <fbff> <fb00>\n"; $stream .= "<fc00> <fcff> <fc00>\n"; $stream .= "<fd00> <fdff> <fd00>\n"; $stream .= "<fe00> <feff> <fe00>\n"; $stream .= "<ff00> <ffff> <ff00>\n"; $stream .= "endbfrange\n"; $stream .= "endcmap\n"; $stream .= "CMapName currentdict /CMap defineresource pop\n"; $stream .= "end\n"; $stream .= "end"; // ToUnicode Object $this->_newobj(); $stream = ($this->compress) ? gzcompress($stream) : $stream; $filter = ($this->compress) ? '/Filter /FlateDecode ' : ''; $stream = $this->_getrawstream($stream); $this->_out('<<'.$filter.'/Length '.strlen($stream).'>> stream'."\n".$stream."\n".'endstream'."\n".'endobj'); // CIDFontType2 // A CIDFont whose glyph descriptions are based on TrueType font technology $oid = $this->_newobj(); $out = '<< /Type /Font'; $out .= ' /Subtype /CIDFontType2'; $out .= ' /BaseFont /'.$fontname; // A dictionary containing entries that define the character collection of the CIDFont. $cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry'], $oid); $cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering'], $oid); $cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement']; $out .= ' /CIDSystemInfo << '.$cidinfo.' >>'; $out .= ' /FontDescriptor '.($this->n + 1).' 0 R'; $out .= ' /DW '.$font['dw']; // default width $out .= "\n".$this->_putfontwidths($font, 0); if (isset($font['ctg']) AND (!$this->empty_string($font['ctg']))) { $out .= "\n".'/CIDToGIDMap '.($this->n + 2).' 0 R'; } $out .= ' >>'; $out .= "\n".'endobj'; $this->_out($out); // Font descriptor // A font descriptor describing the CIDFont default metrics other than its glyph widths $this->_newobj(); $out = '<< /Type /FontDescriptor'; $out .= ' /FontName /'.$fontname; foreach ($font['desc'] as $key => $value) { if(is_float($value)) { $value = sprintf('%.3F', $value); } $out .= ' /'.$key.' '.$value; } $fontdir = false; if (!$this->empty_string($font['file'])) { // A stream containing a TrueType font $out .= ' /FontFile2 '.$this->FontFiles[$font['file']]['n'].' 0 R'; $fontdir = $this->FontFiles[$font['file']]['fontdir']; } $out .= ' >>'; $out .= "\n".'endobj'; $this->_out($out); if (isset($font['ctg']) AND (!$this->empty_string($font['ctg']))) { $this->_newobj(); // Embed CIDToGIDMap // A specification of the mapping from CIDs to glyph indices // search and get CTG font file to embedd $ctgfile = strtolower($font['ctg']); // search and get ctg font file to embedd $fontfile = ''; // search files on various directories if (($fontdir !== false) AND file_exists($fontdir.$ctgfile)) { $fontfile = $fontdir.$ctgfile; } elseif (file_exists($this->_getfontpath().$ctgfile)) { $fontfile = $this->_getfontpath().$ctgfile; } elseif (file_exists($ctgfile)) { $fontfile = $ctgfile; } if ($this->empty_string($fontfile)) { $this->Error('Font file not found: '.$ctgfile); } $stream = $this->_getrawstream(file_get_contents($fontfile)); $out = '<< /Length '.strlen($stream).''; if (substr($fontfile, -2) == '.z') { // check file extension // Decompresses data encoded using the public-domain // zlib/deflate compression method, reproducing the // original text or binary data $out .= ' /Filter /FlateDecode'; } $out .= ' >>'; $out .= ' stream'."\n".$stream."\n".'endstream'; $out .= "\n".'endobj'; $this->_out($out); } } /** * Output CID-0 fonts. * A Type 0 CIDFont contains glyph descriptions based on the Adobe Type 1 font format * @param array $font font data * @access protected * @author Andrew Whitehead, Nicola Asuni, Yukihiro Nakadaira * @since 3.2.000 (2008-06-23) */ protected function _putcidfont0($font) { $cidoffset = 0; if (!isset($font['cw'][1])) { $cidoffset = 31; } if (isset($font['cidinfo']['uni2cid'])) { // convert unicode to cid. $uni2cid = $font['cidinfo']['uni2cid']; $cw = array(); foreach ($font['cw'] as $uni => $width) { if (isset($uni2cid[$uni])) { $cw[($uni2cid[$uni] + $cidoffset)] = $width; } elseif ($uni < 256) { $cw[$uni] = $width; } // else unknown character } $font = array_merge($font, array('cw' => $cw)); } $name = $font['name']; $enc = $font['enc']; if ($enc) { $longname = $name.'-'.$enc; } else { $longname = $name; } $out = $this->_getobj($this->font_obj_ids[$font['fontkey']])."\n"; $out .= '<</Type /Font'; $out .= ' /Subtype /Type0'; $out .= ' /BaseFont /'.$longname; $out .= ' /Name /F'.$font['i']; if ($enc) { $out .= ' /Encoding /'.$enc; } $out .= ' /DescendantFonts ['.($this->n + 1).' 0 R]'; $out .= ' >>'; $out .= "\n".'endobj'; $this->_out($out); $oid = $this->_newobj(); $out = '<</Type /Font'; $out .= ' /Subtype /CIDFontType0'; $out .= ' /BaseFont /'.$name; $cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry'], $oid); $cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering'], $oid); $cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement']; $out .= ' /CIDSystemInfo <<'.$cidinfo.'>>'; $out .= ' /FontDescriptor '.($this->n + 1).' 0 R'; $out .= ' /DW '.$font['dw']; $out .= "\n".$this->_putfontwidths($font, $cidoffset); $out .= ' >>'; $out .= "\n".'endobj'; $this->_out($out); $this->_newobj(); $s = '<</Type /FontDescriptor /FontName /'.$name; foreach ($font['desc'] as $k => $v) { if ($k != 'Style') { if(is_float($v)) { $v = sprintf('%.3F', $v); } $s .= ' /'.$k.' '.$v.''; } } $s .= '>>'; $s .= "\n".'endobj'; $this->_out($s); } /** * Output images. * @access protected */ protected function _putimages() { $filter = ($this->compress) ? '/Filter /FlateDecode ' : ''; foreach ($this->imagekeys as $file) { $info = $this->getImageBuffer($file); $oid = $this->_newobj(); $this->xobjects['I'.$info['i']] = array('n' => $oid); $this->setImageSubBuffer($file, 'n', $this->n); $out = '<</Type /XObject'; $out .= ' /Subtype /Image'; $out .= ' /Width '.$info['w']; $out .= ' /Height '.$info['h']; if (array_key_exists('masked', $info)) { $out .= ' /SMask '.($this->n - 1).' 0 R'; } if ($info['cs'] == 'Indexed') { $out .= ' /ColorSpace [/Indexed /DeviceRGB '.((strlen($info['pal']) / 3) - 1).' '.($this->n + 1).' 0 R]'; } else { $out .= ' /ColorSpace /'.$info['cs']; if ($info['cs'] == 'DeviceCMYK') { $out .= ' /Decode [1 0 1 0 1 0 1 0]'; } } $out .= ' /BitsPerComponent '.$info['bpc']; if (isset($info['f'])) { $out .= ' /Filter /'.$info['f']; } if (isset($info['parms'])) { $out .= ' '.$info['parms']; } if (isset($info['trns']) AND is_array($info['trns'])) { $trns=''; $count_info = count($info['trns']); for ($i=0; $i < $count_info; ++$i) { $trns .= $info['trns'][$i].' '.$info['trns'][$i].' '; } $out .= ' /Mask ['.$trns.']'; } $stream = $this->_getrawstream($info['data']); $out .= ' /Length '.strlen($stream).' >>'; $out .= ' stream'."\n".$stream."\n".'endstream'; $out .= "\n".'endobj'; $this->_out($out); //Palette if ($info['cs'] == 'Indexed') { $this->_newobj(); $pal = ($this->compress) ? gzcompress($info['pal']) : $info['pal']; $pal = $this->_getrawstream($pal); $this->_out('<<'.$filter.'/Length '.strlen($pal).'>> stream'."\n".$pal."\n".'endstream'."\n".'endobj'); } } } /** * Output Form XObjects Templates. * @author Nicola Asuni * @since 5.8.017 (2010-08-24) * @access protected * @see startTemplate(), endTemplate(), printTemplate() */ protected function _putxobjects() { foreach ($this->xobjects as $key => $data) { if (isset($data['outdata'])) { $stream = trim($data['outdata']); $out = $this->_getobj($data['n'])."\n"; $out .= '<<'; $out .= ' /Type /XObject'; $out .= ' /Subtype /Form'; $out .= ' /FormType 1'; if ($this->compress) { $stream = gzcompress($stream); $out .= ' /Filter /FlateDecode'; } $out .= sprintf(' /BBox [0 0 %.2F %.2F]', ($data['w'] * $this->k), ($data['h'] * $this->k)); $out .= ' /Matrix [1 0 0 1 0 0]'; $out .= ' /Resources <<'; $out .= ' /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]'; // fonts if (!empty($data['fonts'])) { $out .= ' /Font <<'; foreach ($data['fonts'] as $fontkey => $fontid) { $out .= ' /F'.$fontid.' '.$this->font_obj_ids[$fontkey].' 0 R'; } $out .= ' >>'; } // images or nested xobjects if (!empty($data['images']) OR !empty($data['xobjects'])) { $out .= ' /XObject <<'; foreach ($data['images'] as $imgid) { $out .= ' /I'.$imgid.' '.$this->xobjects['I'.$imgid]['n'].' 0 R'; } foreach ($data['xobjects'] as $sub_id => $sub_objid) { $out .= ' /'.$sub_id.' '.$sub_objid['n'].' 0 R'; } $out .= ' >>'; } $out .= ' >>'; $stream = $this->_getrawstream($stream); $out .= ' /Length '.strlen($stream); $out .= ' >>'; $out .= ' stream'."\n".$stream."\n".'endstream'; $out .= "\n".'endobj'; $this->_out($out); } } } /** * Output Spot Colors Resources. * @access protected * @since 4.0.024 (2008-09-12) */ protected function _putspotcolors() { foreach ($this->spot_colors as $name => $color) { $this->_newobj(); $this->spot_colors[$name]['n'] = $this->n; $out = '[/Separation /'.str_replace(' ', '#20', $name); $out .= ' /DeviceCMYK <<'; $out .= ' /Range [0 1 0 1 0 1 0 1] /C0 [0 0 0 0]'; $out .= ' '.sprintf('/C1 [%.4F %.4F %.4F %.4F] ', $color['c']/100, $color['m']/100, $color['y']/100, $color['k']/100); $out .= ' /FunctionType 2 /Domain [0 1] /N 1>>]'; $out .= "\n".'endobj'; $this->_out($out); } } /** * Return XObjects Dictionary. * @return string XObjects dictionary * @access protected * @since 5.8.014 (2010-08-23) */ protected function _getxobjectdict() { $out = ''; foreach ($this->xobjects as $id => $objid) { $out .= ' /'.$id.' '.$objid['n'].' 0 R'; } return $out; } /** * Output Resources Dictionary. * @access protected */ protected function _putresourcedict() { $out = $this->_getobj(2)."\n"; $out .= '<< /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]'; $out .= ' /Font <<'; foreach ($this->fontkeys as $fontkey) { $font = $this->getFontBuffer($fontkey); $out .= ' /F'.$font['i'].' '.$font['n'].' 0 R'; } $out .= ' >>'; $out .= ' /XObject <<'; $out .= $this->_getxobjectdict(); $out .= ' >>'; // visibility $out .= ' /Properties <</OC1 '.$this->n_ocg_print.' 0 R /OC2 '.$this->n_ocg_view.' 0 R>>'; // transparency $out .= ' /ExtGState <<'; foreach ($this->extgstates as $k => $extgstate) { if (isset($extgstate['name'])) { $out .= ' /'.$extgstate['name']; } else { $out .= ' /GS'.$k; } $out .= ' '.$extgstate['n'].' 0 R'; } $out .= ' >>'; // gradient patterns if (isset($this->gradients) AND (count($this->gradients) > 0)) { $out .= ' /Pattern <<'; foreach ($this->gradients as $id => $grad) { $out .= ' /p'.$id.' '.$grad['pattern'].' 0 R'; } $out .= ' >>'; } // gradient shadings if (isset($this->gradients) AND (count($this->gradients) > 0)) { $out .= ' /Shading <<'; foreach ($this->gradients as $id => $grad) { $out .= ' /Sh'.$id.' '.$grad['id'].' 0 R'; } $out .= ' >>'; } // spot colors if (isset($this->spot_colors) AND (count($this->spot_colors) > 0)) { $out .= ' /ColorSpace <<'; foreach ($this->spot_colors as $color) { $out .= ' /CS'.$color['i'].' '.$color['n'].' 0 R'; } $out .= ' >>'; } $out .= ' >>'; $out .= "\n".'endobj'; $this->_out($out); } /** * Output Resources. * @access protected */ protected function _putresources() { $this->_putextgstates(); $this->_putocg(); $this->_putfonts(); $this->_putimages(); $this->_putxobjects(); $this->_putspotcolors(); $this->_putshaders(); $this->_putresourcedict(); $this->_putbookmarks(); $this->_putEmbeddedFiles(); $this->_putannotsobjs(); $this->_putjavascript(); $this->_putencryption(); } /** * Adds some Metadata information (Document Information Dictionary) * (see Chapter 14.3.3 Document Information Dictionary of PDF32000_2008.pdf Reference) * @return int object id * @access protected */ protected function _putinfo() { $oid = $this->_newobj(); $out = '<<'; if (!$this->empty_string($this->title)) { // The document's title. $out .= ' /Title '.$this->_textstring($this->title, $oid); } if (!$this->empty_string($this->author)) { // The name of the person who created the document. $out .= ' /Author '.$this->_textstring($this->author, $oid); } if (!$this->empty_string($this->subject)) { // The subject of the document. $out .= ' /Subject '.$this->_textstring($this->subject, $oid); } if (!$this->empty_string($this->keywords)) { // Keywords associated with the document. $out .= ' /Keywords '.$this->_textstring($this->keywords.' TCP'.'DF', $oid); } if (!$this->empty_string($this->creator)) { // If the document was converted to PDF from another format, the name of the conforming product that created the original document from which it was converted. $out .= ' /Creator '.$this->_textstring($this->creator, $oid); } if (defined('PDF_PRODUCER')) { // If the document was converted to PDF from another format, the name of the conforming product that converted it to PDF. $out .= ' /Producer '.$this->_textstring(PDF_PRODUCER.' (TCP'.'DF)', $oid); } else { // default producer $out .= ' /Producer '.$this->_textstring('TCP'.'DF', $oid); } // The date and time the document was created, in human-readable form $out .= ' /CreationDate '.$this->_datestring(); // The date and time the document was most recently modified, in human-readable form $out .= ' /ModDate '.$this->_datestring(); // A name object indicating whether the document has been modified to include trapping information $out .= ' /Trapped /False'; $out .= ' >>'; $out .= "\n".'endobj'; $this->_out($out); return $oid; } /** * Output Catalog. * @return int object id * @access protected */ protected function _putcatalog() { $oid = $this->_newobj(); $out = '<< /Type /Catalog'; $out .= ' /Pages 1 0 R'; if ($this->ZoomMode == 'fullpage') { $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /Fit]'; } elseif ($this->ZoomMode == 'fullwidth') { $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /FitH null]'; } elseif ($this->ZoomMode == 'real') { $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /XYZ null null 1]'; } elseif (!is_string($this->ZoomMode)) { $out .= sprintf(' /OpenAction ['.$this->page_obj_id[1].' 0 R /XYZ null null %.2F]',($this->ZoomMode / 100)); } if (isset($this->LayoutMode) AND (!$this->empty_string($this->LayoutMode))) { $out .= ' /PageLayout /'.$this->LayoutMode; } if (isset($this->PageMode) AND (!$this->empty_string($this->PageMode))) { $out .= ' /PageMode /'.$this->PageMode; } if (isset($this->l['a_meta_language'])) { $out .= ' /Lang '.$this->_textstring($this->l['a_meta_language'], $oid); } $out .= ' /Names <<'; if ((!empty($this->javascript)) OR (!empty($this->js_objects))) { $out .= ' /JavaScript '.($this->n_js).' 0 R'; } $out .= ' >>'; if (count($this->outlines) > 0) { $out .= ' /Outlines '.$this->OutlineRoot.' 0 R'; $out .= ' /PageMode /UseOutlines'; } $out .= ' '.$this->_putviewerpreferences(); $p = $this->n_ocg_print.' 0 R'; $v = $this->n_ocg_view.' 0 R'; $as = '<< /Event /Print /OCGs ['.$p.' '.$v.'] /Category [/Print] >> << /Event /View /OCGs ['.$p.' '.$v.'] /Category [/View] >>'; $out .= ' /OCProperties << /OCGs ['.$p.' '.$v.'] /D << /ON ['.$p.'] /OFF ['.$v.'] /AS ['.$as.'] >> >>'; // AcroForm if (!empty($this->form_obj_id) OR ($this->sign AND isset($this->signature_data['cert_type']))) { $out .= ' /AcroForm <<'; $objrefs = ''; if ($this->sign AND isset($this->signature_data['cert_type'])) { $objrefs .= $this->sig_obj_id.' 0 R'; } if (!empty($this->form_obj_id)) { foreach($this->form_obj_id as $objid) { $objrefs .= ' '.$objid.' 0 R'; } } $out .= ' /Fields ['.$objrefs.']'; if (!empty($this->form_obj_id) AND !$this->sign) { // It's better to turn off this value and set the appearance stream for each annotation (/AP) to avoid conflicts with signature fields. $out .= ' /NeedAppearances true'; } if ($this->sign AND isset($this->signature_data['cert_type'])) { if ($this->signature_data['cert_type'] > 0) { $out .= ' /SigFlags 3'; } else { $out .= ' /SigFlags 1'; } } //$out .= ' /CO '; if (isset($this->annotation_fonts) AND !empty($this->annotation_fonts)) { $out .= ' /DR <<'; $out .= ' /Font <<'; foreach ($this->annotation_fonts as $fontkey => $fontid) { $out .= ' /F'.$fontid.' '.$this->font_obj_ids[$fontkey].' 0 R'; } $out .= ' >> >>'; } $font = $this->getFontBuffer('helvetica'); $out .= ' /DA (/F'.$font['i'].' 0 Tf 0 g)'; $out .= ' /Q '.(($this->rtl)?'2':'0'); //$out .= ' /XFA '; $out .= ' >>'; // signatures if ($this->sign AND isset($this->signature_data['cert_type'])) { if ($this->signature_data['cert_type'] > 0) { $out .= ' /Perms << /DocMDP '.($this->sig_obj_id + 1).' 0 R >>'; } else { $out .= ' /Perms << /UR3 '.($this->sig_obj_id + 1).' 0 R >>'; } } } $out .= ' >>'; $out .= "\n".'endobj'; $this->_out($out); return $oid; } /** * Output viewer preferences. * @return string for viewer preferences * @author Nicola asuni * @since 3.1.000 (2008-06-09) * @access protected */ protected function _putviewerpreferences() { $out = '/ViewerPreferences <<'; if ($this->rtl) { $out .= ' /Direction /R2L'; } else { $out .= ' /Direction /L2R'; } if (isset($this->viewer_preferences['HideToolbar']) AND ($this->viewer_preferences['HideToolbar'])) { $out .= ' /HideToolbar true'; } if (isset($this->viewer_preferences['HideMenubar']) AND ($this->viewer_preferences['HideMenubar'])) { $out .= ' /HideMenubar true'; } if (isset($this->viewer_preferences['HideWindowUI']) AND ($this->viewer_preferences['HideWindowUI'])) { $out .= ' /HideWindowUI true'; } if (isset($this->viewer_preferences['FitWindow']) AND ($this->viewer_preferences['FitWindow'])) { $out .= ' /FitWindow true'; } if (isset($this->viewer_preferences['CenterWindow']) AND ($this->viewer_preferences['CenterWindow'])) { $out .= ' /CenterWindow true'; } if (isset($this->viewer_preferences['DisplayDocTitle']) AND ($this->viewer_preferences['DisplayDocTitle'])) { $out .= ' /DisplayDocTitle true'; } if (isset($this->viewer_preferences['NonFullScreenPageMode'])) { $out .= ' /NonFullScreenPageMode /'.$this->viewer_preferences['NonFullScreenPageMode']; } if (isset($this->viewer_preferences['ViewArea'])) { $out .= ' /ViewArea /'.$this->viewer_preferences['ViewArea']; } if (isset($this->viewer_preferences['ViewClip'])) { $out .= ' /ViewClip /'.$this->viewer_preferences['ViewClip']; } if (isset($this->viewer_preferences['PrintArea'])) { $out .= ' /PrintArea /'.$this->viewer_preferences['PrintArea']; } if (isset($this->viewer_preferences['PrintClip'])) { $out .= ' /PrintClip /'.$this->viewer_preferences['PrintClip']; } if (isset($this->viewer_preferences['PrintScaling'])) { $out .= ' /PrintScaling /'.$this->viewer_preferences['PrintScaling']; } if (isset($this->viewer_preferences['Duplex']) AND (!$this->empty_string($this->viewer_preferences['Duplex']))) { $out .= ' /Duplex /'.$this->viewer_preferences['Duplex']; } if (isset($this->viewer_preferences['PickTrayByPDFSize'])) { if ($this->viewer_preferences['PickTrayByPDFSize']) { $out .= ' /PickTrayByPDFSize true'; } else { $out .= ' /PickTrayByPDFSize false'; } } if (isset($this->viewer_preferences['PrintPageRange'])) { $PrintPageRangeNum = ''; foreach ($this->viewer_preferences['PrintPageRange'] as $k => $v) { $PrintPageRangeNum .= ' '.($v - 1).''; } $out .= ' /PrintPageRange ['.substr($PrintPageRangeNum,1).']'; } if (isset($this->viewer_preferences['NumCopies'])) { $out .= ' /NumCopies '.intval($this->viewer_preferences['NumCopies']); } $out .= ' >>'; return $out; } /** * Output PDF header. * @access protected */ protected function _putheader() { $this->_out('%PDF-'.$this->PDFVersion); } /** * Output end of document (EOF). * @access protected */ protected function _enddoc() { $this->state = 1; $this->_putheader(); $this->_putpages(); $this->_putresources(); // Signature if ($this->sign AND isset($this->signature_data['cert_type'])) { // widget annotation for signature $out = $this->_getobj($this->sig_obj_id)."\n"; $out .= '<< /Type /Annot'; $out .= ' /Subtype /Widget'; $out .= ' /Rect ['.$this->signature_appearance['rect'].']'; $out .= ' /P '.$this->page_obj_id[($this->signature_appearance['page'])].' 0 R'; // link to signature appearance page $out .= ' /F 4'; $out .= ' /FT /Sig'; $out .= ' /T '.$this->_textstring('Signature', $this->sig_obj_id); $out .= ' /Ff 0'; $out .= ' /V '.($this->sig_obj_id + 1).' 0 R'; $out .= ' >>'; $out .= "\n".'endobj'; $this->_out($out); // signature $this->_putsignature(); } // Info $objid_info = $this->_putinfo(); // Catalog $objid_catalog = $this->_putcatalog(); // Cross-ref $o = $this->bufferlen; // XREF section $this->_out('xref'); $this->_out('0 '.($this->n + 1)); $this->_out('0000000000 65535 f '); for ($i=1; $i <= $this->n; ++$i) { $this->_out(sprintf('%010d 00000 n ', $this->offsets[$i])); } // TRAILER $out = 'trailer <<'; $out .= ' /Size '.($this->n + 1); $out .= ' /Root '.$objid_catalog.' 0 R'; $out .= ' /Info '.$objid_info.' 0 R'; if ($this->encrypted) { $out .= ' /Encrypt '.$this->encryptdata['objid'].' 0 R'; } $out .= ' /ID [ <'.$this->file_id.'> <'.$this->file_id.'> ]'; $out .= ' >>'; $this->_out($out); $this->_out('startxref'); $this->_out($o); $this->_out('%%EOF'); $this->state = 3; // end-of-doc if ($this->diskcache) { // remove temporary files used for images foreach ($this->imagekeys as $key) { // remove temporary files unlink($this->images[$key]); } foreach ($this->fontkeys as $key) { // remove temporary files unlink($this->fonts[$key]); } } } /** * Initialize a new page. * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul> * @param mixed $format The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() or an array of parameters specified at setPageFormat(). * @access protected * @see getPageSizeFromFormat(), setPageFormat() */ protected function _beginpage($orientation='', $format='') { ++$this->page; $this->setPageBuffer($this->page, ''); // initialize array for graphics tranformation positions inside a page buffer $this->transfmrk[$this->page] = array(); $this->state = 2; if ($this->empty_string($orientation)) { if (isset($this->CurOrientation)) { $orientation = $this->CurOrientation; } elseif ($this->fwPt > $this->fhPt) { // landscape $orientation = 'L'; } else { // portrait $orientation = 'P'; } } if ($this->empty_string($format)) { $this->pagedim[$this->page] = $this->pagedim[($this->page - 1)]; $this->setPageOrientation($orientation); } else { $this->setPageFormat($format, $orientation); } if ($this->rtl) { $this->x = $this->w - $this->rMargin; } else { $this->x = $this->lMargin; } $this->y = $this->tMargin; if (isset($this->newpagegroup[$this->page])) { // start a new group $n = sizeof($this->pagegroups) + 1; $alias = '{nb'.$n.'}'; $this->pagegroups[$alias] = 1; $this->currpagegroup = $alias; } elseif ($this->currpagegroup) { ++$this->pagegroups[$this->currpagegroup]; } } /** * Mark end of page. * @access protected */ protected function _endpage() { $this->setVisibility('all'); $this->state = 1; } /** * Begin a new object and return the object number. * @return int object number * @access protected */ protected function _newobj() { $this->_out($this->_getobj()); return $this->n; } /** * Return the starting object string for the selected object ID. * @param int $objid Object ID (leave empty to get a new ID). * @return string the starting object string * @access protected * @since 5.8.009 (2010-08-20) */ protected function _getobj($objid='') { if ($objid === '') { ++$this->n; $objid = $this->n; } $this->offsets[$objid] = $this->bufferlen; return $objid.' 0 obj'; } /** * Underline text. * @param int $x X coordinate * @param int $y Y coordinate * @param string $txt text to underline * @access protected */ protected function _dounderline($x, $y, $txt) { $w = $this->GetStringWidth($txt); return $this->_dounderlinew($x, $y, $w); } /** * Underline for rectangular text area. * @param int $x X coordinate * @param int $y Y coordinate * @param int $w width to underline * @access protected * @since 4.8.008 (2009-09-29) */ protected function _dounderlinew($x, $y, $w) { $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt; return sprintf('%.2F %.2F %.2F %.2F re f', $x * $this->k, ((($this->h - $y) * $this->k) + $linew), $w * $this->k, $linew); } /** * Line through text. * @param int $x X coordinate * @param int $y Y coordinate * @param string $txt text to linethrough * @access protected */ protected function _dolinethrough($x, $y, $txt) { $w = $this->GetStringWidth($txt); return $this->_dolinethroughw($x, $y, $w); } /** * Line through for rectangular text area. * @param int $x X coordinate * @param int $y Y coordinate * @param string $txt text to linethrough * @access protected * @since 4.9.008 (2009-09-29) */ protected function _dolinethroughw($x, $y, $w) { $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt; return sprintf('%.2F %.2F %.2F %.2F re f', $x * $this->k, ((($this->h - $y) * $this->k) + $linew + ($this->FontSizePt / 3)), $w * $this->k, $linew); } /** * Overline text. * @param int $x X coordinate * @param int $y Y coordinate * @param string $txt text to overline * @access protected * @since 4.9.015 (2010-04-19) */ protected function _dooverline($x, $y, $txt) { $w = $this->GetStringWidth($txt); return $this->_dooverlinew($x, $y, $w); } /** * Overline for rectangular text area. * @param int $x X coordinate * @param int $y Y coordinate * @param int $w width to overline * @access protected * @since 4.9.015 (2010-04-19) */ protected function _dooverlinew($x, $y, $w) { $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt; return sprintf('%.2F %.2F %.2F %.2F re f', $x * $this->k, (($this->h - $y + $this->FontAscent) * $this->k) - $linew, $w * $this->k, $linew); } /** * Read a 4-byte (32 bit) integer from file. * @param string $f file name. * @return 4-byte integer * @access protected */ protected function _freadint($f) { $a = unpack('Ni', fread($f, 4)); return $a['i']; } /** * Add "\" before "\", "(" and ")" * @param string $s string to escape. * @return string escaped string. * @access protected */ protected function _escape($s) { // the chr(13) substitution fixes the Bugs item #1421290. return strtr($s, array(')' => '\\)', '(' => '\\(', '\\' => '\\\\', chr(13) => '\r')); } /** * Format a data string for meta information * @param string $s data string to escape. * @param int $n object ID * @return string escaped string. * @access protected */ protected function _datastring($s, $n=0) { if ($n == 0) { $n = $this->n; } $s = $this->_encrypt_data($n, $s); return '('. $this->_escape($s).')'; } /** * Returns a formatted date for meta information * @param int $n object ID * @return string escaped date string. * @access protected * @since 4.6.028 (2009-08-25) */ protected function _datestring($n=0) { $current_time = substr_replace(date('YmdHisO'), '\'', (0 - 2), 0).'\''; return $this->_datastring('D:'.$current_time, $n); } /** * Format a text string for meta information * @param string $s string to escape. * @param int $n object ID * @return string escaped string. * @access protected */ protected function _textstring($s, $n=0) { if ($this->isunicode) { //Convert string to UTF-16BE $s = $this->UTF8ToUTF16BE($s, true); } return $this->_datastring($s, $n); } /** * THIS METHOD IS DEPRECATED * Format a text string * @param string $s string to escape. * @return string escaped string. * @access protected * @deprecated */ protected function _escapetext($s) { if ($this->isunicode) { if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) { $s = $this->UTF8ToLatin1($s); } else { //Convert string to UTF-16BE and reverse RTL language $s = $this->utf8StrRev($s, false, $this->tmprtl); } } return $this->_escape($s); } /** * get raw output stream. * @param string $s string to output. * @param int $n object reference for encryption mode * @access protected * @author Nicola Asuni * @since 5.5.000 (2010-06-22) */ protected function _getrawstream($s, $n=0) { if ($n <= 0) { // default to current object $n = $this->n; } return $this->_encrypt_data($n, $s); } /** * Format output stream (DEPRECATED). * @param string $s string to output. * @param int $n object reference for encryption mode * @access protected * @deprecated */ protected function _getstream($s, $n=0) { return 'stream'."\n".$this->_getrawstream($s, $n)."\n".'endstream'; } /** * Output a stream (DEPRECATED). * @param string $s string to output. * @param int $n object reference for encryption mode * @access protected * @deprecated */ protected function _putstream($s, $n=0) { $this->_out($this->_getstream($s, $n)); } /** * Output a string to the document. * @param string $s string to output. * @access protected */ protected function _out($s) { if ($this->state == 2) { if ($this->inxobj) { // we are inside an XObject template $this->xobjects[$this->xobjid]['outdata'] .= $s."\n"; } elseif ((!$this->InFooter) AND isset($this->footerlen[$this->page]) AND ($this->footerlen[$this->page] > 0)) { // puts data before page footer $pagebuff = $this->getPageBuffer($this->page); $page = substr($pagebuff, 0, -$this->footerlen[$this->page]); $footer = substr($pagebuff, -$this->footerlen[$this->page]); $this->setPageBuffer($this->page, $page.$s."\n".$footer); // update footer position $this->footerpos[$this->page] += strlen($s."\n"); } else { $this->setPageBuffer($this->page, $s."\n", true); } } else { $this->setBuffer($s."\n"); } } /** * Converts UTF-8 strings to codepoints array.<br> * Invalid byte sequences will be replaced with 0xFFFD (replacement character)<br> * Based on: http://www.faqs.org/rfcs/rfc3629.html * <pre> * Char. number range | UTF-8 octet sequence * (hexadecimal) | (binary) * --------------------+----------------------------------------------- * 0000 0000-0000 007F | 0xxxxxxx * 0000 0080-0000 07FF | 110xxxxx 10xxxxxx * 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx * 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx * --------------------------------------------------------------------- * * ABFN notation: * --------------------------------------------------------------------- * UTF8-octets = *( UTF8-char ) * UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4 * UTF8-1 = %x00-7F * UTF8-2 = %xC2-DF UTF8-tail * * UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) / * %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail ) * UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) / * %xF4 %x80-8F 2( UTF8-tail ) * UTF8-tail = %x80-BF * --------------------------------------------------------------------- * </pre> * @param string $str string to process. * @return array containing codepoints (UTF-8 characters values) * @access protected * @author Nicola Asuni * @since 1.53.0.TC005 (2005-01-05) */ protected function UTF8StringToArray($str) { // build a unique string key $strkey = md5($str); if (isset($this->cache_UTF8StringToArray[$strkey])) { // return cached value $chrarray = $this->cache_UTF8StringToArray[$strkey]['s']; if (!isset($this->cache_UTF8StringToArray[$strkey]['f'][$this->CurrentFont['fontkey']])) { if ($this->isunicode) { foreach ($chrarray as $chr) { // store this char for font subsetting $this->CurrentFont['subsetchars'][$chr] = true; } // update font subsetchars $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']); } $this->cache_UTF8StringToArray[$strkey]['f'][$this->CurrentFont['fontkey']] = true; } return $chrarray; } // check cache size if ($this->cache_size_UTF8StringToArray >= $this->cache_maxsize_UTF8StringToArray) { // remove first element array_shift($this->cache_UTF8StringToArray); } // new cache array for selected string $this->cache_UTF8StringToArray[$strkey] = array('s' => array(), 'f' => array()); ++$this->cache_size_UTF8StringToArray; if (!$this->isunicode) { // split string into array of equivalent codes $strarr = array(); $strlen = strlen($str); for ($i=0; $i < $strlen; ++$i) { $strarr[] = ord($str{$i}); } // insert new value on cache $this->cache_UTF8StringToArray[$strkey]['s'] = $strarr; $this->cache_UTF8StringToArray[$strkey]['f'][$this->CurrentFont['fontkey']] = true; return $strarr; } $unichar = -1; // last unicode char $unicode = array(); // array containing unicode values $bytes = array(); // array containing single character byte sequences $numbytes = 1; // number of octetc needed to represent the UTF-8 character $str .= ''; // force $str to be a string $length = strlen($str); for ($i = 0; $i < $length; ++$i) { $char = ord($str{$i}); // get one string character at time if (count($bytes) == 0) { // get starting octect if ($char <= 0x7F) { $unichar = $char; // use the character "as is" because is ASCII $numbytes = 1; } elseif (($char >> 0x05) == 0x06) { // 2 bytes character (0x06 = 110 BIN) $bytes[] = ($char - 0xC0) << 0x06; $numbytes = 2; } elseif (($char >> 0x04) == 0x0E) { // 3 bytes character (0x0E = 1110 BIN) $bytes[] = ($char - 0xE0) << 0x0C; $numbytes = 3; } elseif (($char >> 0x03) == 0x1E) { // 4 bytes character (0x1E = 11110 BIN) $bytes[] = ($char - 0xF0) << 0x12; $numbytes = 4; } else { // use replacement character for other invalid sequences $unichar = 0xFFFD; $bytes = array(); $numbytes = 1; } } elseif (($char >> 0x06) == 0x02) { // bytes 2, 3 and 4 must start with 0x02 = 10 BIN $bytes[] = $char - 0x80; if (count($bytes) == $numbytes) { // compose UTF-8 bytes to a single unicode value $char = $bytes[0]; for ($j = 1; $j < $numbytes; ++$j) { $char += ($bytes[$j] << (($numbytes - $j - 1) * 0x06)); } if ((($char >= 0xD800) AND ($char <= 0xDFFF)) OR ($char >= 0x10FFFF)) { /* The definition of UTF-8 prohibits encoding character numbers between U+D800 and U+DFFF, which are reserved for use with the UTF-16 encoding form (as surrogate pairs) and do not directly represent characters. */ $unichar = 0xFFFD; // use replacement character } else { $unichar = $char; // add char to array } // reset data for next char $bytes = array(); $numbytes = 1; } } else { // use replacement character for other invalid sequences $unichar = 0xFFFD; $bytes = array(); $numbytes = 1; } if ($unichar >= 0) { // insert unicode value into array $unicode[] = $unichar; // store this char for font subsetting $this->CurrentFont['subsetchars'][$unichar] = true; $unichar = -1; } } // update font subsetchars $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']); // insert new value on cache $this->cache_UTF8StringToArray[$strkey]['s'] = $unicode; $this->cache_UTF8StringToArray[$strkey]['f'][$this->CurrentFont['fontkey']] = true; return $unicode; } /** * Converts UTF-8 strings to UTF16-BE.<br> * @param string $str string to process. * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF) * @return string * @access protected * @author Nicola Asuni * @since 1.53.0.TC005 (2005-01-05) * @uses UTF8StringToArray(), arrUTF8ToUTF16BE() */ protected function UTF8ToUTF16BE($str, $setbom=true) { if (!$this->isunicode) { return $str; // string is not in unicode } $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values return $this->arrUTF8ToUTF16BE($unicode, $setbom); } /** * Converts UTF-8 strings to Latin1 when using the standard 14 core fonts.<br> * @param string $str string to process. * @return string * @author Andrew Whitehead, Nicola Asuni * @access protected * @since 3.2.000 (2008-06-23) */ protected function UTF8ToLatin1($str) { global $utf8tolatin; if (!$this->isunicode) { return $str; // string is not in unicode } $outstr = ''; // string to be returned $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values foreach ($unicode as $char) { if ($char < 256) { $outstr .= chr($char); } elseif (array_key_exists($char, $utf8tolatin)) { // map from UTF-8 $outstr .= chr($utf8tolatin[$char]); } elseif ($char == 0xFFFD) { // skip } else { $outstr .= '?'; } } return $outstr; } /** * Converts UTF-8 characters array to array of Latin1 characters<br> * @param array $unicode array containing UTF-8 unicode values * @return array * @author Nicola Asuni * @access protected * @since 4.8.023 (2010-01-15) */ protected function UTF8ArrToLatin1($unicode) { global $utf8tolatin; if ((!$this->isunicode) OR $this->isUnicodeFont()) { return $unicode; } $outarr = array(); // array to be returned foreach ($unicode as $char) { if ($char < 256) { $outarr[] = $char; } elseif (array_key_exists($char, $utf8tolatin)) { // map from UTF-8 $outarr[] = $utf8tolatin[$char]; } elseif ($char == 0xFFFD) { // skip } else { $outarr[] = 63; // '?' character } } return $outarr; } /** * Converts array of UTF-8 characters to UTF16-BE string.<br> * Based on: http://www.faqs.org/rfcs/rfc2781.html * <pre> * Encoding UTF-16: * * Encoding of a single character from an ISO 10646 character value to * UTF-16 proceeds as follows. Let U be the character number, no greater * than 0x10FFFF. * * 1) If U < 0x10000, encode U as a 16-bit unsigned integer and * terminate. * * 2) Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF, * U' must be less than or equal to 0xFFFFF. That is, U' can be * represented in 20 bits. * * 3) Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and * 0xDC00, respectively. These integers each have 10 bits free to * encode the character value, for a total of 20 bits. * * 4) Assign the 10 high-order bits of the 20-bit U' to the 10 low-order * bits of W1 and the 10 low-order bits of U' to the 10 low-order * bits of W2. Terminate. * * Graphically, steps 2 through 4 look like: * U' = yyyyyyyyyyxxxxxxxxxx * W1 = 110110yyyyyyyyyy * W2 = 110111xxxxxxxxxx * </pre> * @param array $unicode array containing UTF-8 unicode values * @param boolean $setbom if true set the Byte Order Mark (BOM = 0xFEFF) * @return string * @access protected * @author Nicola Asuni * @since 2.1.000 (2008-01-08) * @see UTF8ToUTF16BE() */ protected function arrUTF8ToUTF16BE($unicode, $setbom=true) { $outstr = ''; // string to be returned if ($setbom) { $outstr .= "\xFE\xFF"; // Byte Order Mark (BOM) } foreach ($unicode as $char) { if ($char == 0x200b) { // skip Unicode Character 'ZERO WIDTH SPACE' (DEC:8203, U+200B) } elseif ($char == 0xFFFD) { $outstr .= "\xFF\xFD"; // replacement character } elseif ($char < 0x10000) { $outstr .= chr($char >> 0x08); $outstr .= chr($char & 0xFF); } else { $char -= 0x10000; $w1 = 0xD800 | ($char >> 0x10); $w2 = 0xDC00 | ($char & 0x3FF); $outstr .= chr($w1 >> 0x08); $outstr .= chr($w1 & 0xFF); $outstr .= chr($w2 >> 0x08); $outstr .= chr($w2 & 0xFF); } } return $outstr; } // ==================================================== /** * Set header font. * @param array $font font * @access public * @since 1.1 */ public function setHeaderFont($font) { $this->header_font = $font; } /** * Get header font. * @return array() * @access public * @since 4.0.012 (2008-07-24) */ public function getHeaderFont() { return $this->header_font; } /** * Set footer font. * @param array $font font * @access public * @since 1.1 */ public function setFooterFont($font) { $this->footer_font = $font; } /** * Get Footer font. * @return array() * @access public * @since 4.0.012 (2008-07-24) */ public function getFooterFont() { return $this->footer_font; } /** * Set language array. * @param array $language * @access public * @since 1.1 */ public function setLanguageArray($language) { $this->l = $language; if (isset($this->l['a_meta_dir'])) { $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false; } else { $this->rtl = false; } } /** * Returns the PDF data. * @access public */ public function getPDFData() { if ($this->state < 3) { $this->Close(); } return $this->buffer; } /** * Output anchor link. * @param string $url link URL or internal link (i.e.: &lt;a href="#23"&gt;link to page 23&lt;/a&gt;) * @param string $name link name * @param boolean $fill Indicates if the cell background must be painted (true) or transparent (false). * @param boolean $firstline if true prints only the first line and return the remaining string. * @param array $color array of RGB text color * @param string $style font style (U, D, B, I) * @param boolean $firstblock if true the string is the starting of a line. * @return the number of cells used or the remaining text if $firstline = true; * @access public */ public function addHtmlLink($url, $name, $fill=false, $firstline=false, $color='', $style=-1, $firstblock=false) { if (!$this->empty_string($url) AND ($url{0} == '#')) { // convert url to internal link $page = intval(substr($url, 1)); $url = $this->AddLink(); $this->SetLink($url, 0, $page); } // store current settings $prevcolor = $this->fgcolor; $prevstyle = $this->FontStyle; if (empty($color)) { $this->SetTextColorArray($this->htmlLinkColorArray); } else { $this->SetTextColorArray($color); } if ($style == -1) { $this->SetFont('', $this->FontStyle.$this->htmlLinkFontStyle); } else { $this->SetFont('', $this->FontStyle.$style); } $ret = $this->Write($this->lasth, $name, $url, $fill, '', false, 0, $firstline, $firstblock, 0); // restore settings $this->SetFont('', $prevstyle); $this->SetTextColorArray($prevcolor); return $ret; } /** * Returns an associative array (keys: R,G,B) from an html color name or a six-digit or three-digit hexadecimal color representation (i.e. #3FE5AA or #7FF). * @param string $color html color * @return array RGB color or false in case of error. * @access public */ public function convertHTMLColorToDec($color='#FFFFFF') { global $webcolor; $returncolor = false; $color = preg_replace('/[\s]*/', '', $color); // remove extra spaces $color = strtolower($color); if (($dotpos = strpos($color, '.')) !== false) { // remove class parent (i.e.: color.red) $color = substr($color, ($dotpos + 1)); } if (strlen($color) == 0) { return false; } // RGB ARRAY if (substr($color, 0, 3) == 'rgb') { $codes = substr($color, 4); $codes = str_replace(')', '', $codes); $returncolor = explode(',', $codes); return $returncolor; } // CMYK ARRAY if (substr($color, 0, 4) == 'cmyk') { $codes = substr($color, 5); $codes = str_replace(')', '', $codes); $returncolor = explode(',', $codes); return $returncolor; } // COLOR NAME if (substr($color, 0, 1) != '#') { // decode color name if (isset($webcolor[$color])) { $color_code = $webcolor[$color]; } else { return false; } } else { $color_code = substr($color, 1); } // RGB VALUE switch (strlen($color_code)) { case 3: { // three-digit hexadecimal representation $r = substr($color_code, 0, 1); $g = substr($color_code, 1, 1); $b = substr($color_code, 2, 1); $returncolor['R'] = hexdec($r.$r); $returncolor['G'] = hexdec($g.$g); $returncolor['B'] = hexdec($b.$b); break; } case 6: { // six-digit hexadecimal representation $returncolor['R'] = hexdec(substr($color_code, 0, 2)); $returncolor['G'] = hexdec(substr($color_code, 2, 2)); $returncolor['B'] = hexdec(substr($color_code, 4, 2)); break; } } return $returncolor; } /** * Converts pixels to User's Units. * @param int $px pixels * @return float value in user's unit * @access public * @see setImageScale(), getImageScale() */ public function pixelsToUnits($px) { return ($px / ($this->imgscale * $this->k)); } /** * Reverse function for htmlentities. * Convert entities in UTF-8. * @param string $text_to_convert Text to convert. * @return string converted text string * @access public */ public function unhtmlentities($text_to_convert) { return html_entity_decode($text_to_convert, ENT_QUOTES, $this->encoding); } // ENCRYPTION METHODS ---------------------------------- /** * Compute encryption key depending on object number where the encrypted data is stored. * This is used for all strings and streams without crypt filter specifier. * @param int $n object number * @access protected * @author Nicola Asuni * @since 2.0.000 (2008-01-02) */ protected function _objectkey($n) { $objkey = $this->encryptdata['key'].pack('VXxx', $n); if ($this->encryptdata['mode'] == 2) { // AES padding $objkey .= "\x73\x41\x6C\x54"; } $objkey = substr($this->_md5_16($objkey), 0, (($this->encryptdata['Length'] / 8) + 5)); $objkey = substr($objkey, 0, 16); return $objkey; } /** * Encrypt the input string. * @param int $n object number * @param string $s data string to encrypt * @access protected * @author Nicola Asuni * @since 5.0.005 (2010-05-11) */ protected function _encrypt_data($n, $s) { if (!$this->encrypted) { return $s; } switch ($this->encryptdata['mode']) { case 0: // RC4 40 bit case 1: { // RC4 128 bit $s = $this->_RC4($this->_objectkey($n), $s); break; } case 2: { // AES 128 bit $s = $this->_AES($this->_objectkey($n), $s); break; } } return $s; } /** * Put encryption on PDF document. * @access protected * @author Nicola Asuni * @since 2.0.000 (2008-01-02) */ protected function _putencryption() { if (!$this->encrypted) { return; } $this->encryptdata['objid'] = $this->_newobj(); $out = '<<'; if (!isset($this->encryptdata['Filter']) OR empty($this->encryptdata['Filter'])) { $this->encryptdata['Filter'] = 'Standard'; } $out .= ' /Filter /'.$this->encryptdata['Filter']; if (isset($this->encryptdata['SubFilter']) AND !empty($this->encryptdata['SubFilter'])) { $out .= ' /SubFilter /'.$this->encryptdata['SubFilter']; } if (!isset($this->encryptdata['V']) OR empty($this->encryptdata['V'])) { $this->encryptdata['V'] = 1; } // V is a code specifying the algorithm to be used in encrypting and decrypting the document $out .= ' /V '.$this->encryptdata['V']; if ($this->encryptdata['V'] == 1) { $out .= ' /Length 40'; } elseif (($this->encryptdata['V'] == 2) OR ($this->encryptdata['V'] == 3)) { if (isset($this->encryptdata['Length']) AND !empty($this->encryptdata['Length'])) { // The length of the encryption key, in bits. The value shall be a multiple of 8, in the range 40 to 128 $out .= ' /Length '.$this->encryptdata['Length']; } else { $out .= ' /Length 40'; } } elseif ($this->encryptdata['V'] == 4) { if (!isset($this->encryptdata['StmF']) OR empty($this->encryptdata['StmF'])) { $this->encryptdata['StmF'] = 'Identity'; } if (!isset($this->encryptdata['StrF']) OR empty($this->encryptdata['StrF'])) { // The name of the crypt filter that shall be used when decrypting all strings in the document. $this->encryptdata['StrF'] = 'Identity'; } // A dictionary whose keys shall be crypt filter names and whose values shall be the corresponding crypt filter dictionaries. if (isset($this->encryptdata['CF']) AND !empty($this->encryptdata['CF'])) { $out .= ' /CF <<'; $out .= ' /'.$this->encryptdata['StmF'].' <<'; $out .= ' /Type /CryptFilter'; if (isset($this->encryptdata['CF']['CFM']) AND !empty($this->encryptdata['CF']['CFM'])) { // The method used $out .= ' /CFM /'.$this->encryptdata['CF']['CFM']; if ($this->encryptdata['pubkey']) { $out .= ' /Recipients ['; foreach ($this->encryptdata['Recipients'] as $rec) { $out .= ' <'.$rec.'>'; } $out .= ' ]'; if (isset($this->encryptdata['CF']['EncryptMetadata']) AND (!$this->encryptdata['CF']['EncryptMetadata'])) { $out .= ' /EncryptMetadata false'; } else { $out .= ' /EncryptMetadata true'; } } } else { $out .= ' /CFM /None'; } if (isset($this->encryptdata['CF']['AuthEvent']) AND !empty($this->encryptdata['CF']['AuthEvent'])) { // The event to be used to trigger the authorization that is required to access encryption keys used by this filter. $out .= ' /AuthEvent /'.$this->encryptdata['CF']['AuthEvent']; } else { $out .= ' /AuthEvent /DocOpen'; } if (isset($this->encryptdata['CF']['Length']) AND !empty($this->encryptdata['CF']['Length'])) { // The bit length of the encryption key. $out .= ' /Length '.$this->encryptdata['CF']['Length']; } $out .= ' >> >>'; } // The name of the crypt filter that shall be used by default when decrypting streams. $out .= ' /StmF /'.$this->encryptdata['StmF']; // The name of the crypt filter that shall be used when decrypting all strings in the document. $out .= ' /StrF /'.$this->encryptdata['StrF']; if (isset($this->encryptdata['EFF']) AND !empty($this->encryptdata['EFF'])) { // The name of the crypt filter that shall be used when encrypting embedded file streams that do not have their own crypt filter specifier. $out .= ' /EFF /'.$this->encryptdata['']; } } // Additional encryption dictionary entries for the standard security handler if ($this->encryptdata['pubkey']) { if (($this->encryptdata['V'] < 4) AND isset($this->encryptdata['Recipients']) AND !empty($this->encryptdata['Recipients'])) { $out .= ' /Recipients ['; foreach ($this->encryptdata['Recipients'] as $rec) { $out .= ' <'.$rec.'>'; } $out .= ' ]'; } } else { $out .= ' /R'; if ($this->encryptdata['V'] == 4) { $out .= ' 4'; } elseif ($this->encryptdata['V'] < 2) { $out .= ' 2'; } else { $out .= ' 3'; } $out .= ' /O ('.$this->_escape($this->encryptdata['O']).')'; $out .= ' /U ('.$this->_escape($this->encryptdata['U']).')'; $out .= ' /P '.$this->encryptdata['P']; if (isset($this->encryptdata['EncryptMetadata']) AND (!$this->encryptdata['EncryptMetadata'])) { $out .= ' /EncryptMetadata false'; } else { $out .= ' /EncryptMetadata true'; } } $out .= ' >>'; $out .= "\n".'endobj'; $this->_out($out); } /** * Returns the input text exrypted using RC4 algorithm and the specified key. * RC4 is the standard encryption algorithm used in PDF format * @param string $key encryption key * @param String $text input text to be encrypted * @return String encrypted text * @access protected * @since 2.0.000 (2008-01-02) * @author Klemen Vodopivec, Nicola Asuni */ protected function _RC4($key, $text) { if (function_exists('mcrypt_decrypt') AND ($out = @mcrypt_decrypt(MCRYPT_ARCFOUR, $key, $text, MCRYPT_MODE_STREAM, ''))) { // try to use mcrypt function if exist return $out; } if ($this->last_enc_key != $key) { $k = str_repeat($key, ((256 / strlen($key)) + 1)); $rc4 = range(0, 255); $j = 0; for ($i = 0; $i < 256; ++$i) { $t = $rc4[$i]; $j = ($j + $t + ord($k{$i})) % 256; $rc4[$i] = $rc4[$j]; $rc4[$j] = $t; } $this->last_enc_key = $key; $this->last_enc_key_c = $rc4; } else { $rc4 = $this->last_enc_key_c; } $len = strlen($text); $a = 0; $b = 0; $out = ''; for ($i = 0; $i < $len; ++$i) { $a = ($a + 1) % 256; $t = $rc4[$a]; $b = ($b + $t) % 256; $rc4[$a] = $rc4[$b]; $rc4[$b] = $t; $k = $rc4[($rc4[$a] + $rc4[$b]) % 256]; $out .= chr(ord($text{$i}) ^ $k); } return $out; } /** * Returns the input text exrypted using AES algorithm and the specified key. * This method requires mcrypt. * @param string $key encryption key * @param String $text input text to be encrypted * @return String encrypted text * @access protected * @author Nicola Asuni * @since 5.0.005 (2010-05-11) */ protected function _AES($key, $text) { // padding (RFC 2898, PKCS #5: Password-Based Cryptography Specification Version 2.0) $padding = 16 - (strlen($text) % 16); $text .= str_repeat(chr($padding), $padding); $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND); $text = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $text, MCRYPT_MODE_CBC, $iv); $text = $iv.$text; return $text; } /** * Encrypts a string using MD5 and returns it's value as a binary string. * @param string $str input string * @return String MD5 encrypted binary string * @access protected * @since 2.0.000 (2008-01-02) * @author Klemen Vodopivec */ protected function _md5_16($str) { return pack('H*', md5($str)); } /** * Compute O value (used for encryption) * @param String $user_pass user password * @param String $owner_pass user password * @return String O value * @access protected * @since 2.0.000 (2008-01-02) * @author Nicola Asuni */ protected function _Ovalue($user_pass, $owner_pass) { $tmp = $this->_md5_16($owner_pass); if ($this->encryptdata['mode'] > 0) { for ($i = 0; $i < 50; ++$i) { $tmp = $this->_md5_16($tmp); } } $owner_key = substr($tmp, 0, ($this->encryptdata['Length'] / 8)); $enc = $this->_RC4($owner_key, $user_pass); if ($this->encryptdata['mode'] > 0) { $len = strlen($owner_key); for ($i = 1; $i <= 19; ++$i) { $ek = ''; for ($j = 0; $j < $len; ++$j) { $ek .= chr(ord($owner_key{$j}) ^ $i); } $enc = $this->_RC4($ek, $enc); } } return $enc; } /** * Compute U value (used for encryption) * @return String U value * @access protected * @since 2.0.000 (2008-01-02) * @author Nicola Asuni */ protected function _Uvalue() { if ($this->encryptdata['mode'] == 0) { return $this->_RC4($this->encryptdata['key'], $this->enc_padding); } $tmp = $this->_md5_16($this->enc_padding.$this->encryptdata['fileid']); $enc = $this->_RC4($this->encryptdata['key'], $tmp); $len = strlen($tmp); for ($i = 1; $i <= 19; ++$i) { $ek = ''; for ($j = 0; $j < $len; ++$j) { $ek .= chr(ord($this->encryptdata['key']{$j}) ^ $i); } $enc = $this->_RC4($ek, $enc); } $enc .= str_repeat("\x00", 16); return substr($enc, 0, 32); } /** * Compute encryption key * @param String $user_pass user password * @param String $owner_pass user password * @param String $protection protection type * @access protected * @since 2.0.000 (2008-01-02) * @author Nicola Asuni */ protected function _generateencryptionkey($user_pass, $owner_pass, $protection) { $keybytelen = ($this->encryptdata['Length'] / 8); if (!$this->encryptdata['pubkey']) { // standard mode // Pad passwords $user_pass = substr($user_pass.$this->enc_padding, 0, 32); $owner_pass = substr($owner_pass.$this->enc_padding, 0, 32); // Compute O value $this->encryptdata['O'] = $this->_Ovalue($user_pass, $owner_pass); // get default permissions (reverse byte order) $permissions = $this->getEncPermissionsString($protection); // Compute encryption key $tmp = $this->_md5_16($user_pass.$this->encryptdata['O'].$permissions.$this->encryptdata['fileid']); if ($this->encryptdata['mode'] > 0) { for ($i = 0; $i < 50; ++$i) { $tmp = $this->_md5_16(substr($tmp, 0, $keybytelen)); } } $this->encryptdata['key'] = substr($tmp, 0, $keybytelen); // Compute U value $this->encryptdata['U'] = $this->_Uvalue(); // Compute P value $this->encryptdata['P'] = $protection; } else { // Public-Key mode // random 20-byte seed $seed = sha1(microtime().uniqid(''.rand()).$this->file_id, true); $recipient_bytes = ''; foreach ($this->encryptdata['pubkeys'] as $pubkey) { // for each public certificate if (isset($pubkey['p'])) { $pkprotection = $this->getUserPermissionCode($pubkey['p'], $this->encryptdata['mode']); } else { $pkprotection = $protection; } // get default permissions (reverse byte order) $pkpermissions = $this->getEncPermissionsString($pkprotection); // envelope data $envelope = $seed.$pkpermissions; // write the envelope data to a temporary file $tempkeyfile = tempnam(K_PATH_CACHE, 'tmpkey_'); $f = fopen($tempkeyfile, 'wb'); if (!$f) { $this->Error('Unable to create temporary key file: '.$tempkeyfile); } $envelope_lenght = strlen($envelope); fwrite($f, $envelope, $envelope_lenght); fclose($f); $tempencfile = tempnam(K_PATH_CACHE, 'tmpenc_'); if (!openssl_pkcs7_encrypt($tempkeyfile, $tempencfile, $pubkey['c'], array(), PKCS7_DETACHED | PKCS7_BINARY)) { $this->Error('Unable to encrypt the file: '.$tempkeyfile); } unlink($tempkeyfile); // read encryption signature $signature = file_get_contents($tempencfile, false, null, $envelope_lenght); unlink($tempencfile); // extract signature $signature = substr($signature, strpos($signature, 'Content-Disposition')); $tmparr = explode("\n\n", $signature); $signature = trim($tmparr[1]); unset($tmparr); // decode signature $signature = base64_decode($signature); // convert signature to hex $hexsignature = current(unpack('H*', $signature)); // store signature on recipients array $this->encryptdata['Recipients'][] = $hexsignature; // The bytes of each item in the Recipients array of PKCS#7 objects in the order in which they appear in the array $recipient_bytes .= $signature; } // calculate encryption key $this->encryptdata['key'] = substr(sha1($seed.$recipient_bytes, true), 0, $keybytelen); } } /** * Return the premission code used on encryption (P value). * @param Array $permissions the set of permissions (specify the ones you want to block). * @param int $mode encryption strength: 0 = RC4 40 bit; 1 = RC4 128 bit; 2 = AES 128 bit. * @access protected * @since 5.0.005 (2010-05-12) * @author Nicola Asuni */ protected function getUserPermissionCode($permissions, $mode=0) { $options = array( 'owner' => 2, // bit 2 -- inverted logic: cleared by default 'print' => 4, // bit 3 'modify' => 8, // bit 4 'copy' => 16, // bit 5 'annot-forms' => 32, // bit 6 'fill-forms' => 256, // bit 9 'extract' => 512, // bit 10 'assemble' => 1024,// bit 11 'print-high' => 2048 // bit 12 ); $protection = 2147422012; // (01111111111111110000111100111100) foreach ($permissions as $permission) { if (!isset($options[$permission])) { $this->Error('Incorrect permission: '.$permission); } if (($mode > 0) OR ($options[$permission] <= 32)) { // set only valid permissions if ($options[$permission] == 2) { // the logic for bit 2 is inverted (cleared by default) $protection += $options[$permission]; } else { $protection -= $options[$permission]; } } } return $protection; } /** * Set document protection * Remark: the protection against modification is for people who have the full Acrobat product. * If you don't set any password, the document will open as usual. If you set a user password, the PDF viewer will ask for it before displaying the document. The master password, if different from the user one, can be used to get full access. * Note: protecting a document requires to encrypt it, which increases the processing time a lot. This can cause a PHP time-out in some cases, especially if the document contains images or fonts. * @param Array $permissions the set of permissions (specify the ones you want to block):<ul><li>print : Print the document;</li><li>modify : Modify the contents of the document by operations other than those controlled by 'fill-forms', 'extract' and 'assemble';</li><li>copy : Copy or otherwise extract text and graphics from the document;</li><li>annot-forms : Add or modify text annotations, fill in interactive form fields, and, if 'modify' is also set, create or modify interactive form fields (including signature fields);</li><li>fill-forms : Fill in existing interactive form fields (including signature fields), even if 'annot-forms' is not specified;</li><li>extract : Extract text and graphics (in support of accessibility to users with disabilities or for other purposes);</li><li>assemble : Assemble the document (insert, rotate, or delete pages and create bookmarks or thumbnail images), even if 'modify' is not set;</li><li>print-high : Print the document to a representation from which a faithful digital copy of the PDF content could be generated. When this is not set, printing is limited to a low-level representation of the appearance, possibly of degraded quality.</li><li>owner : (inverted logic - only for public-key) when set permits change of encryption and enables all other permissions.</li></ul> * @param String $user_pass user password. Empty by default. * @param String $owner_pass owner password. If not specified, a random value is used. * @param int $mode encryption strength: 0 = RC4 40 bit; 1 = RC4 128 bit; 2 = AES 128 bit. * @param String $pubkeys array of recipients containing public-key certificates ('c') and permissions ('p'). For example: array(array('c' => 'file://../tcpdf.crt', 'p' => array('print'))) * @access public * @since 2.0.000 (2008-01-02) * @author Nicola Asuni */ public function SetProtection($permissions=array('print', 'modify', 'copy', 'annot-forms', 'fill-forms', 'extract', 'assemble', 'print-high'), $user_pass='', $owner_pass=null, $mode=0, $pubkeys=null) { $protection = $this->getUserPermissionCode($permissions, $mode); if (($pubkeys !== null) AND (is_array($pubkeys))) { // public-key mode $this->encryptdata['pubkeys'] = $pubkeys; if ($mode == 0) { // public-Key Security requires at least 128 bit $mode = 1; } if (!function_exists('openssl_pkcs7_encrypt')) { $this->Error('Public-Key Security requires openssl library.'); } // Set Public-Key filter (availabe are: Entrust.PPKEF, Adobe.PPKLite, Adobe.PubSec) $this->encryptdata['pubkey'] = true; $this->encryptdata['Filter'] = 'Adobe.PubSec'; $this->encryptdata['StmF'] = 'DefaultCryptFilter'; $this->encryptdata['StrF'] = 'DefaultCryptFilter'; } else { // standard mode (password mode) $this->encryptdata['pubkey'] = false; $this->encryptdata['Filter'] = 'Standard'; $this->encryptdata['StmF'] = 'StdCF'; $this->encryptdata['StrF'] = 'StdCF'; } if ($mode > 1) { // AES if (!extension_loaded('mcrypt')) { $this->Error('AES encryption requires mcrypt library.'); } if (mcrypt_get_cipher_name(MCRYPT_RIJNDAEL_128) === false) { $this->Error('AES encryption requires MCRYPT_RIJNDAEL_128 cypher.'); } } if ($owner_pass === null) { $owner_pass = uniqid(''.rand()); } $this->encryptdata['mode'] = $mode; switch ($mode) { case 0: { // RC4 40 bit $this->encryptdata['V'] = 1; $this->encryptdata['Length'] = 40; $this->encryptdata['CF']['CFM'] = 'V2'; break; } case 1: { // RC4 128 bit $this->encryptdata['V'] = 2; $this->encryptdata['Length'] = 128; $this->encryptdata['CF']['CFM'] = 'V2'; if ($this->encryptdata['pubkey']) { $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s4'; $this->encryptdata['Recipients'] = array(); } break; } case 2: { // AES 128 bit $this->encryptdata['V'] = 4; $this->encryptdata['Length'] = 128; $this->encryptdata['CF']['CFM'] = 'AESV2'; if ($this->encryptdata['pubkey']) { $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s5'; $this->encryptdata['Recipients'] = array(); } break; } } $this->encrypted = true; $this->encryptdata['fileid'] = $this->convertHexStringToString($this->file_id); $this->_generateencryptionkey($user_pass, $owner_pass, $protection); } /** * Convert hexadecimal string to string * @param string $bs byte-string to convert * @return String * @access protected * @since 5.0.005 (2010-05-12) * @author Nicola Asuni */ protected function convertHexStringToString($bs) { $string = ''; // string to be returned $bslenght = strlen($bs); if (($bslenght % 2) != 0) { // padding $bs .= '0'; ++$bslenght; } for ($i = 0; $i < $bslenght; $i += 2) { $string .= chr(hexdec($bs{$i}.$bs{($i + 1)})); } return $string; } /** * Convert string to hexadecimal string (byte string) * @param string $s string to convert * @return byte string * @access protected * @since 5.0.010 (2010-05-17) * @author Nicola Asuni */ protected function convertStringToHexString($s) { $bs = ''; $chars = preg_split('//', $s, -1, PREG_SPLIT_NO_EMPTY); foreach ($chars as $c) { $bs .= sprintf('%02s', dechex(ord($c))); } return $bs; } /** * Convert encryption P value to a string of bytes, low-order byte first. * @param string $protection 32bit encryption permission value (P value) * @return String * @access protected * @since 5.0.005 (2010-05-12) * @author Nicola Asuni */ protected function getEncPermissionsString($protection) { $binprot = sprintf('%032b', $protection); $str = chr(bindec(substr($binprot, 24, 8))); $str .= chr(bindec(substr($binprot, 16, 8))); $str .= chr(bindec(substr($binprot, 8, 8))); $str .= chr(bindec(substr($binprot, 0, 8))); return $str; } // END OF ENCRYPTION FUNCTIONS ------------------------- // START TRANSFORMATIONS SECTION ----------------------- /** * Starts a 2D tranformation saving current graphic state. * This function must be called before scaling, mirroring, translation, rotation and skewing. * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior. * @access public * @since 2.1.000 (2008-01-07) * @see StartTransform(), StopTransform() */ public function StartTransform() { $this->_out('q'); $this->transfmrk[$this->page][] = $this->pagelen[$this->page]; ++$this->transfmatrix_key; $this->transfmatrix[$this->transfmatrix_key] = array(); } /** * Stops a 2D tranformation restoring previous graphic state. * This function must be called after scaling, mirroring, translation, rotation and skewing. * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior. * @access public * @since 2.1.000 (2008-01-07) * @see StartTransform(), StopTransform() */ public function StopTransform() { $this->_out('Q'); if (isset($this->transfmatrix[$this->transfmatrix_key])) { array_pop($this->transfmatrix[$this->transfmatrix_key]); --$this->transfmatrix_key; } array_pop($this->transfmrk[$this->page]); } /** * Horizontal Scaling. * @param float $s_x scaling factor for width as percent. 0 is not allowed. * @param int $x abscissa of the scaling center. Default is current x position * @param int $y ordinate of the scaling center. Default is current y position * @access public * @since 2.1.000 (2008-01-07) * @see StartTransform(), StopTransform() */ public function ScaleX($s_x, $x='', $y='') { $this->Scale($s_x, 100, $x, $y); } /** * Vertical Scaling. * @param float $s_y scaling factor for height as percent. 0 is not allowed. * @param int $x abscissa of the scaling center. Default is current x position * @param int $y ordinate of the scaling center. Default is current y position * @access public * @since 2.1.000 (2008-01-07) * @see StartTransform(), StopTransform() */ public function ScaleY($s_y, $x='', $y='') { $this->Scale(100, $s_y, $x, $y); } /** * Vertical and horizontal proportional Scaling. * @param float $s scaling factor for width and height as percent. 0 is not allowed. * @param int $x abscissa of the scaling center. Default is current x position * @param int $y ordinate of the scaling center. Default is current y position * @access public * @since 2.1.000 (2008-01-07) * @see StartTransform(), StopTransform() */ public function ScaleXY($s, $x='', $y='') { $this->Scale($s, $s, $x, $y); } /** * Vertical and horizontal non-proportional Scaling. * @param float $s_x scaling factor for width as percent. 0 is not allowed. * @param float $s_y scaling factor for height as percent. 0 is not allowed. * @param int $x abscissa of the scaling center. Default is current x position * @param int $y ordinate of the scaling center. Default is current y position * @access public * @since 2.1.000 (2008-01-07) * @see StartTransform(), StopTransform() */ public function Scale($s_x, $s_y, $x='', $y='') { if ($x === '') { $x = $this->x; } if ($y === '') { $y = $this->y; } if (($s_x == 0) OR ($s_y == 0)) { $this->Error('Please do not use values equal to zero for scaling'); } $y = ($this->h - $y) * $this->k; $x *= $this->k; //calculate elements of transformation matrix $s_x /= 100; $s_y /= 100; $tm = array(); $tm[0] = $s_x; $tm[1] = 0; $tm[2] = 0; $tm[3] = $s_y; $tm[4] = $x * (1 - $s_x); $tm[5] = $y * (1 - $s_y); //scale the coordinate system $this->Transform($tm); } /** * Horizontal Mirroring. * @param int $x abscissa of the point. Default is current x position * @access public * @since 2.1.000 (2008-01-07) * @see StartTransform(), StopTransform() */ public function MirrorH($x='') { $this->Scale(-100, 100, $x); } /** * Verical Mirroring. * @param int $y ordinate of the point. Default is current y position * @access public * @since 2.1.000 (2008-01-07) * @see StartTransform(), StopTransform() */ public function MirrorV($y='') { $this->Scale(100, -100, '', $y); } /** * Point reflection mirroring. * @param int $x abscissa of the point. Default is current x position * @param int $y ordinate of the point. Default is current y position * @access public * @since 2.1.000 (2008-01-07) * @see StartTransform(), StopTransform() */ public function MirrorP($x='',$y='') { $this->Scale(-100, -100, $x, $y); } /** * Reflection against a straight line through point (x, y) with the gradient angle (angle). * @param float $angle gradient angle of the straight line. Default is 0 (horizontal line). * @param int $x abscissa of the point. Default is current x position * @param int $y ordinate of the point. Default is current y position * @access public * @since 2.1.000 (2008-01-07) * @see StartTransform(), StopTransform() */ public function MirrorL($angle=0, $x='',$y='') { $this->Scale(-100, 100, $x, $y); $this->Rotate(-2*($angle-90), $x, $y); } /** * Translate graphic object horizontally. * @param int $t_x movement to the right (or left for RTL) * @access public * @since 2.1.000 (2008-01-07) * @see StartTransform(), StopTransform() */ public function TranslateX($t_x) { $this->Translate($t_x, 0); } /** * Translate graphic object vertically. * @param int $t_y movement to the bottom * @access public * @since 2.1.000 (2008-01-07) * @see StartTransform(), StopTransform() */ public function TranslateY($t_y) { $this->Translate(0, $t_y); } /** * Translate graphic object horizontally and vertically. * @param int $t_x movement to the right * @param int $t_y movement to the bottom * @access public * @since 2.1.000 (2008-01-07) * @see StartTransform(), StopTransform() */ public function Translate($t_x, $t_y) { //calculate elements of transformation matrix $tm = array(); $tm[0] = 1; $tm[1] = 0; $tm[2] = 0; $tm[3] = 1; $tm[4] = $t_x * $this->k; $tm[5] = -$t_y * $this->k; //translate the coordinate system $this->Transform($tm); } /** * Rotate object. * @param float $angle angle in degrees for counter-clockwise rotation * @param int $x abscissa of the rotation center. Default is current x position * @param int $y ordinate of the rotation center. Default is current y position * @access public * @since 2.1.000 (2008-01-07) * @see StartTransform(), StopTransform() */ public function Rotate($angle, $x='', $y='') { if ($x === '') { $x = $this->x; } if ($y === '') { $y = $this->y; } $y = ($this->h - $y) * $this->k; $x *= $this->k; //calculate elements of transformation matrix $tm = array(); $tm[0] = cos(deg2rad($angle)); $tm[1] = sin(deg2rad($angle)); $tm[2] = -$tm[1]; $tm[3] = $tm[0]; $tm[4] = $x + ($tm[1] * $y) - ($tm[0] * $x); $tm[5] = $y - ($tm[0] * $y) - ($tm[1] * $x); //rotate the coordinate system around ($x,$y) $this->Transform($tm); } /** * Skew horizontally. * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right) * @param int $x abscissa of the skewing center. default is current x position * @param int $y ordinate of the skewing center. default is current y position * @access public * @since 2.1.000 (2008-01-07) * @see StartTransform(), StopTransform() */ public function SkewX($angle_x, $x='', $y='') { $this->Skew($angle_x, 0, $x, $y); } /** * Skew vertically. * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top) * @param int $x abscissa of the skewing center. default is current x position * @param int $y ordinate of the skewing center. default is current y position * @access public * @since 2.1.000 (2008-01-07) * @see StartTransform(), StopTransform() */ public function SkewY($angle_y, $x='', $y='') { $this->Skew(0, $angle_y, $x, $y); } /** * Skew. * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right) * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top) * @param int $x abscissa of the skewing center. default is current x position * @param int $y ordinate of the skewing center. default is current y position * @access public * @since 2.1.000 (2008-01-07) * @see StartTransform(), StopTransform() */ public function Skew($angle_x, $angle_y, $x='', $y='') { if ($x === '') { $x = $this->x; } if ($y === '') { $y = $this->y; } if (($angle_x <= -90) OR ($angle_x >= 90) OR ($angle_y <= -90) OR ($angle_y >= 90)) { $this->Error('Please use values between -90 and +90 degrees for Skewing.'); } $x *= $this->k; $y = ($this->h - $y) * $this->k; //calculate elements of transformation matrix $tm = array(); $tm[0] = 1; $tm[1] = tan(deg2rad($angle_y)); $tm[2] = tan(deg2rad($angle_x)); $tm[3] = 1; $tm[4] = -$tm[2] * $y; $tm[5] = -$tm[1] * $x; //skew the coordinate system $this->Transform($tm); } /** * Apply graphic transformations. * @param array $tm transformation matrix * @access protected * @since 2.1.000 (2008-01-07) * @see StartTransform(), StopTransform() */ protected function Transform($tm) { $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', $tm[0], $tm[1], $tm[2], $tm[3], $tm[4], $tm[5])); // add tranformation matrix $this->transfmatrix[$this->transfmatrix_key][] = array('a' => $tm[0], 'b' => $tm[1], 'c' => $tm[2], 'd' => $tm[3], 'e' => $tm[4], 'f' => $tm[5]); // update tranformation mark if (end($this->transfmrk[$this->page]) !== false) { $key = key($this->transfmrk[$this->page]); $this->transfmrk[$this->page][$key] = $this->pagelen[$this->page]; } } // END TRANSFORMATIONS SECTION ------------------------- // START GRAPHIC FUNCTIONS SECTION --------------------- // The following section is based on the code provided by David Hernandez Sanz /** * Defines the line width. By default, the value equals 0.2 mm. The method can be called before the first page is created and the value is retained from page to page. * @param float $width The width. * @access public * @since 1.0 * @see Line(), Rect(), Cell(), MultiCell() */ public function SetLineWidth($width) { //Set line width $this->LineWidth = $width; $this->linestyleWidth = sprintf('%.2F w', ($width * $this->k)); if ($this->page > 0) { $this->_out($this->linestyleWidth); } } /** * Returns the current the line width. * @return int Line width * @access public * @since 2.1.000 (2008-01-07) * @see Line(), SetLineWidth() */ public function GetLineWidth() { return $this->LineWidth; } /** * Set line style. * @param array $style Line style. Array with keys among the following: * <ul> * <li>width (float): Width of the line in user units.</li> * <li>cap (string): Type of cap to put on the line. Possible values are: * butt, round, square. The difference between "square" and "butt" is that * "square" projects a flat end past the end of the line.</li> * <li>join (string): Type of join. Possible values are: miter, round, * bevel.</li> * <li>dash (mixed): Dash pattern. Is 0 (without dash) or string with * series of length values, which are the lengths of the on and off dashes. * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on, * 1 off, 2 on, 1 off, ...</li> * <li>phase (integer): Modifier on the dash pattern which is used to shift * the point at which the pattern starts.</li> * <li>color (array): Draw color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K).</li> * </ul> * @param boolean $ret if true do not send the command. * @return string the PDF command * @access public * @since 2.1.000 (2008-01-08) */ public function SetLineStyle($style, $ret=false) { $s = ''; // string to be returned if (!is_array($style)) { return; } extract($style); if (isset($width)) { $this->LineWidth = $width; $this->linestyleWidth = sprintf('%.2F w', ($width * $this->k)); $s .= $this->linestyleWidth.' '; } if (isset($cap)) { $ca = array('butt' => 0, 'round'=> 1, 'square' => 2); if (isset($ca[$cap])) { $this->linestyleCap = $ca[$cap].' J'; $s .= $this->linestyleCap.' '; } } if (isset($join)) { $ja = array('miter' => 0, 'round' => 1, 'bevel' => 2); if (isset($ja[$join])) { $this->linestyleJoin = $ja[$join].' j'; $s .= $this->linestyleJoin.' '; } } if (isset($dash)) { $dash_string = ''; if ($dash) { if (preg_match('/^.+,/', $dash) > 0) { $tab = explode(',', $dash); } else { $tab = array($dash); } $dash_string = ''; foreach ($tab as $i => $v) { if ($i) { $dash_string .= ' '; } $dash_string .= sprintf('%.2F', $v); } } if (!isset($phase) OR !$dash) { $phase = 0; } $this->linestyleDash = sprintf('[%s] %.2F d', $dash_string, $phase); $s .= $this->linestyleDash.' '; } if (isset($color)) { $s .= $this->SetDrawColorArray($color, true).' '; } if (!$ret) { $this->_out($s); } return $s; } /** * Begin a new subpath by moving the current point to coordinates (x, y), omitting any connecting line segment. * @param float $x Abscissa of point. * @param float $y Ordinate of point. * @access protected * @since 2.1.000 (2008-01-08) */ protected function _outPoint($x, $y) { $this->_out(sprintf('%.2F %.2F m', $x * $this->k, ($this->h - $y) * $this->k)); } /** * Append a straight line segment from the current point to the point (x, y). * The new current point shall be (x, y). * @param float $x Abscissa of end point. * @param float $y Ordinate of end point. * @access protected * @since 2.1.000 (2008-01-08) */ protected function _outLine($x, $y) { $this->_out(sprintf('%.2F %.2F l', $x * $this->k, ($this->h - $y) * $this->k)); } /** * Append a rectangle to the current path as a complete subpath, with lower-left corner (x, y) and dimensions widthand height in user space. * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language). * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language). * @param float $w Width. * @param float $h Height. * @param string $op options * @access protected * @since 2.1.000 (2008-01-08) */ protected function _outRect($x, $y, $w, $h, $op) { $this->_out(sprintf('%.2F %.2F %.2F %.2F re %s', $x * $this->k, ($this->h - $y) * $this->k, $w * $this->k, -$h * $this->k, $op)); } /** * Append a cubic Bézier curve to the current path. The curve shall extend from the current point to the point (x3, y3), using (x1, y1) and (x2, y2) as the Bézier control points. * The new current point shall be (x3, y3). * @param float $x1 Abscissa of control point 1. * @param float $y1 Ordinate of control point 1. * @param float $x2 Abscissa of control point 2. * @param float $y2 Ordinate of control point 2. * @param float $x3 Abscissa of end point. * @param float $y3 Ordinate of end point. * @access protected * @since 2.1.000 (2008-01-08) */ protected function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) { $this->_out(sprintf('%.2F %.2F %.2F %.2F %.2F %.2F c', $x1 * $this->k, ($this->h - $y1) * $this->k, $x2 * $this->k, ($this->h - $y2) * $this->k, $x3 * $this->k, ($this->h - $y3) * $this->k)); } /** * Append a cubic Bézier curve to the current path. The curve shall extend from the current point to the point (x3, y3), using the current point and (x2, y2) as the Bézier control points. * The new current point shall be (x3, y3). * @param float $x2 Abscissa of control point 2. * @param float $y2 Ordinate of control point 2. * @param float $x3 Abscissa of end point. * @param float $y3 Ordinate of end point. * @access protected * @since 4.9.019 (2010-04-26) */ protected function _outCurveV($x2, $y2, $x3, $y3) { $this->_out(sprintf('%.2F %.2F %.2F %.2F v', $x2 * $this->k, ($this->h - $y2) * $this->k, $x3 * $this->k, ($this->h - $y3) * $this->k)); } /** * Append a cubic Bézier curve to the current path. The curve shall extend from the current point to the point (x3, y3), using (x1, y1) and (x3, y3) as the Bézier control points. * The new current point shall be (x3, y3). * @param float $x1 Abscissa of control point 1. * @param float $y1 Ordinate of control point 1. * @param float $x2 Abscissa of control point 2. * @param float $y2 Ordinate of control point 2. * @param float $x3 Abscissa of end point. * @param float $y3 Ordinate of end point. * @access protected * @since 2.1.000 (2008-01-08) */ protected function _outCurveY($x1, $y1, $x3, $y3) { $this->_out(sprintf('%.2F %.2F %.2F %.2F y', $x1 * $this->k, ($this->h - $y1) * $this->k, $x3 * $this->k, ($this->h - $y3) * $this->k)); } /** * Draws a line between two points. * @param float $x1 Abscissa of first point. * @param float $y1 Ordinate of first point. * @param float $x2 Abscissa of second point. * @param float $y2 Ordinate of second point. * @param array $style Line style. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array). * @access public * @since 1.0 * @see SetLineWidth(), SetDrawColor(), SetLineStyle() */ public function Line($x1, $y1, $x2, $y2, $style=array()) { if (is_array($style)) { $this->SetLineStyle($style); } $this->_outPoint($x1, $y1); $this->_outLine($x2, $y2); $this->_out('S'); } /** * Draws a rectangle. * @param float $x Abscissa of upper-left corner (or upper-right corner for RTL language). * @param float $y Ordinate of upper-left corner (or upper-right corner for RTL language). * @param float $w Width. * @param float $h Height. * @param string $style Style of rendering. See the getPathPaintOperator() function for more information. * @param array $border_style Border style of rectangle. Array with keys among the following: * <ul> * <li>all: Line style of all borders. Array like for {@link SetLineStyle SetLineStyle}.</li> * <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for {@link SetLineStyle SetLineStyle}.</li> * </ul> * If a key is not present or is null, not draws the border. Default value: default line style (empty array). * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array). * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array). * @access public * @since 1.0 * @see SetLineStyle() */ public function Rect($x, $y, $w, $h, $style='', $border_style=array(), $fill_color=array()) { if (!(false === strpos($style, 'F')) AND !empty($fill_color)) { $this->SetFillColorArray($fill_color); } $op = $this->getPathPaintOperator($style); if ((!$border_style) OR (isset($border_style['all']))) { if (isset($border_style['all']) AND $border_style['all']) { $this->SetLineStyle($border_style['all']); $border_style = array(); } } $this->_outRect($x, $y, $w, $h, $op); if ($border_style) { $border_style2 = array(); foreach ($border_style as $line => $value) { $length = strlen($line); for ($i = 0; $i < $length; ++$i) { $border_style2[$line[$i]] = $value; } } $border_style = $border_style2; if (isset($border_style['L']) AND $border_style['L']) { $this->Line($x, $y, $x, $y + $h, $border_style['L']); } if (isset($border_style['T']) AND $border_style['T']) { $this->Line($x, $y, $x + $w, $y, $border_style['T']); } if (isset($border_style['R']) AND $border_style['R']) { $this->Line($x + $w, $y, $x + $w, $y + $h, $border_style['R']); } if (isset($border_style['B']) AND $border_style['B']) { $this->Line($x, $y + $h, $x + $w, $y + $h, $border_style['B']); } } } /** * Draws a Bezier curve. * The Bezier curve is a tangent to the line between the control points at * either end of the curve. * @param float $x0 Abscissa of start point. * @param float $y0 Ordinate of start point. * @param float $x1 Abscissa of control point 1. * @param float $y1 Ordinate of control point 1. * @param float $x2 Abscissa of control point 2. * @param float $y2 Ordinate of control point 2. * @param float $x3 Abscissa of end point. * @param float $y3 Ordinate of end point. * @param string $style Style of rendering. See the getPathPaintOperator() function for more information. * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array). * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array). * @access public * @see SetLineStyle() * @since 2.1.000 (2008-01-08) */ public function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style='', $line_style=array(), $fill_color=array()) { if (!(false === strpos($style, 'F')) AND isset($fill_color)) { $this->SetFillColorArray($fill_color); } $op = $this->getPathPaintOperator($style); if ($line_style) { $this->SetLineStyle($line_style); } $this->_outPoint($x0, $y0); $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3); $this->_out($op); } /** * Draws a poly-Bezier curve. * Each Bezier curve segment is a tangent to the line between the control points at * either end of the curve. * @param float $x0 Abscissa of start point. * @param float $y0 Ordinate of start point. * @param float $segments An array of bezier descriptions. Format: array(x1, y1, x2, y2, x3, y3). * @param string $style Style of rendering. See the getPathPaintOperator() function for more information. * @param array $line_style Line style of curve. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array). * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array). * @access public * @see SetLineStyle() * @since 3.0008 (2008-05-12) */ public function Polycurve($x0, $y0, $segments, $style='', $line_style=array(), $fill_color=array()) { if (!(false === strpos($style, 'F')) AND isset($fill_color)) { $this->SetFillColorArray($fill_color); } $op = $this->getPathPaintOperator($style); if ($op == 'f') { $line_style = array(); } if ($line_style) { $this->SetLineStyle($line_style); } $this->_outPoint($x0, $y0); foreach ($segments as $segment) { list($x1, $y1, $x2, $y2, $x3, $y3) = $segment; $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3); } $this->_out($op); } /** * Draws an ellipse. * An ellipse is formed from n Bezier curves. * @param float $x0 Abscissa of center point. * @param float $y0 Ordinate of center point. * @param float $rx Horizontal radius. * @param float $ry Vertical radius (if ry = 0 then is a circle, see {@link Circle Circle}). Default value: 0. * @param float $angle: Angle oriented (anti-clockwise). Default value: 0. * @param float $astart: Angle start of draw line. Default value: 0. * @param float $afinish: Angle finish of draw line. Default value: 360. * @param string $style Style of rendering. See the getPathPaintOperator() function for more information. * @param array $line_style Line style of ellipse. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array). * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array). * @param integer $nc Number of curves used to draw a 90 degrees portion of ellipse. * @author Nicola Asuni * @access public * @since 2.1.000 (2008-01-08) */ public function Ellipse($x0, $y0, $rx, $ry='', $angle=0, $astart=0, $afinish=360, $style='', $line_style=array(), $fill_color=array(), $nc=2) { if ($this->empty_string($ry) OR ($ry == 0)) { $ry = $rx; } if (!(false === strpos($style, 'F')) AND isset($fill_color)) { $this->SetFillColorArray($fill_color); } $op = $this->getPathPaintOperator($style); if ($op == 'f') { $line_style = array(); } if ($line_style) { $this->SetLineStyle($line_style); } $this->_outellipticalarc($x0, $y0, $rx, $ry, $angle, $astart, $afinish, false, $nc); $this->_out($op); } /** * Append an elliptical arc to the current path. * An ellipse is formed from n Bezier curves. * @param float $xc Abscissa of center point. * @param float $yc Ordinate of center point. * @param float $rx Horizontal radius. * @param float $ry Vertical radius (if ry = 0 then is a circle, see {@link Circle Circle}). Default value: 0. * @param float $xang: Angle between the X-axis and the major axis of the ellipse. Default value: 0. * @param float $angs: Angle start of draw line. Default value: 0. * @param float $angf: Angle finish of draw line. Default value: 360. * @param boolean $pie if true do not mark the border point (used to draw pie sectors). * @param integer $nc Number of curves used to draw a 90 degrees portion of ellipse. * @author Nicola Asuni * @access protected * @since 4.9.019 (2010-04-26) */ protected function _outellipticalarc($xc, $yc, $rx, $ry, $xang=0, $angs=0, $angf=360, $pie=false, $nc=2) { $k = $this->k; if ($nc < 2) { $nc = 2; } if ($pie) { // center of the arc $this->_outPoint($xc, $yc); } $xang = deg2rad((float) $xang); $angs = deg2rad((float) $angs); $angf = deg2rad((float) $angf); $as = atan2((sin($angs) / $ry), (cos($angs) / $rx)); $af = atan2((sin($angf) / $ry), (cos($angf) / $rx)); if ($as < 0) { $as += (2 * M_PI); } if ($af < 0) { $af += (2 * M_PI); } if ($as > $af) { // reverse rotation go clockwise $as -= (2 * M_PI); } $total_angle = ($af - $as); if ($nc < 2) { $nc = 2; } // total arcs to draw $nc *= (2 * abs($total_angle) / M_PI); $nc = round($nc) + 1; // angle of each arc $arcang = $total_angle / $nc; // center point in PDF coordiantes $x0 = $xc; $y0 = ($this->h - $yc); // starting angle $ang = $as; $alpha = sin($arcang) * ((sqrt(4 + (3 * pow(tan(($arcang) / 2), 2))) - 1) / 3); $cos_xang = cos($xang); $sin_xang = sin($xang); $cos_ang = cos($ang); $sin_ang = sin($ang); // first arc point $px1 = $x0 + ($rx * $cos_xang * $cos_ang) - ($ry * $sin_xang * $sin_ang); $py1 = $y0 + ($rx * $sin_xang * $cos_ang) + ($ry * $cos_xang * $sin_ang); // first Bezier control point $qx1 = ($alpha * ((-$rx * $cos_xang * $sin_ang) - ($ry * $sin_xang * $cos_ang))); $qy1 = ($alpha * ((-$rx * $sin_xang * $sin_ang) + ($ry * $cos_xang * $cos_ang))); if ($pie) { $this->_outLine($px1, $this->h - $py1); } else { $this->_outPoint($px1, $this->h - $py1); } // draw arcs for ($i = 1; $i <= $nc; ++$i) { // starting angle $ang = $as + ($i * $arcang); $cos_xang = cos($xang); $sin_xang = sin($xang); $cos_ang = cos($ang); $sin_ang = sin($ang); // second arc point $px2 = $x0 + ($rx * $cos_xang * $cos_ang) - ($ry * $sin_xang * $sin_ang); $py2 = $y0 + ($rx * $sin_xang * $cos_ang) + ($ry * $cos_xang * $sin_ang); // second Bezier control point $qx2 = ($alpha * ((-$rx * $cos_xang * $sin_ang) - ($ry * $sin_xang * $cos_ang))); $qy2 = ($alpha * ((-$rx * $sin_xang * $sin_ang) + ($ry * $cos_xang * $cos_ang))); // draw arc $this->_outCurve(($px1 + $qx1), ($this->h - ($py1 + $qy1)), ($px2 - $qx2), ($this->h - ($py2 - $qy2)), $px2, ($this->h - $py2)); // move to next point $px1 = $px2; $py1 = $py2; $qx1 = $qx2; $qy1 = $qy2; } if ($pie) { $this->_outLine($xc, $yc); } } /** * Draws a circle. * A circle is formed from n Bezier curves. * @param float $x0 Abscissa of center point. * @param float $y0 Ordinate of center point. * @param float $r Radius. * @param float $angstr: Angle start of draw line. Default value: 0. * @param float $angend: Angle finish of draw line. Default value: 360. * @param string $style Style of rendering. See the getPathPaintOperator() function for more information. * @param array $line_style Line style of circle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array). * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array). * @param integer $nc Number of curves used to draw a 90 degrees portion of circle. * @access public * @since 2.1.000 (2008-01-08) */ public function Circle($x0, $y0, $r, $angstr=0, $angend=360, $style='', $line_style=array(), $fill_color=array(), $nc=2) { $this->Ellipse($x0, $y0, $r, $r, 0, $angstr, $angend, $style, $line_style, $fill_color, $nc); } /** * Draws a polygonal line * @param array $p Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1)) * @param string $style Style of rendering. See the getPathPaintOperator() function for more information. * @param array $line_style Line style of polygon. Array with keys among the following: * <ul> * <li>all: Line style of all lines. Array like for {@link SetLineStyle SetLineStyle}.</li> * <li>0 to ($np - 1): Line style of each line. Array like for {@link SetLineStyle SetLineStyle}.</li> * </ul> * If a key is not present or is null, not draws the line. Default value is default line style (empty array). * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array). * @param boolean $closed if true the polygon is closes, otherwise will remain open * @access public * @since 4.8.003 (2009-09-15) */ public function PolyLine($p, $style='', $line_style=array(), $fill_color=array()) { $this->Polygon($p, $style, $line_style, $fill_color, false); } /** * Draws a polygon. * @param array $p Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1)) * @param string $style Style of rendering. See the getPathPaintOperator() function for more information. * @param array $line_style Line style of polygon. Array with keys among the following: * <ul> * <li>all: Line style of all lines. Array like for {@link SetLineStyle SetLineStyle}.</li> * <li>0 to ($np - 1): Line style of each line. Array like for {@link SetLineStyle SetLineStyle}.</li> * </ul> * If a key is not present or is null, not draws the line. Default value is default line style (empty array). * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array). * @param boolean $closed if true the polygon is closes, otherwise will remain open * @access public * @since 2.1.000 (2008-01-08) */ public function Polygon($p, $style='', $line_style=array(), $fill_color=array(), $closed=true) { $nc = count($p); // number of coordinates $np = $nc / 2; // number of points if ($closed) { // close polygon by adding the first 2 points at the end (one line) for ($i = 0; $i < 4; ++$i) { $p[$nc + $i] = $p[$i]; } // copy style for the last added line if (isset($line_style[0])) { $line_style[$np] = $line_style[0]; } $nc += 4; } if (!(false === strpos($style, 'F')) AND isset($fill_color)) { $this->SetFillColorArray($fill_color); } $op = $this->getPathPaintOperator($style); if ($op == 'f') { $line_style = array(); } $draw = true; if ($line_style) { if (isset($line_style['all'])) { $this->SetLineStyle($line_style['all']); } else { $draw = false; if ($op == 'B') { // draw fill $op = 'f'; $this->_outPoint($p[0], $p[1]); for ($i = 2; $i < $nc; $i = $i + 2) { $this->_outLine($p[$i], $p[$i + 1]); } $this->_out($op); } // draw outline $this->_outPoint($p[0], $p[1]); for ($i = 2; $i < $nc; $i = $i + 2) { $line_num = ($i / 2) - 1; if (isset($line_style[$line_num])) { if ($line_style[$line_num] != 0) { if (is_array($line_style[$line_num])) { $this->_out('S'); $this->SetLineStyle($line_style[$line_num]); $this->_outPoint($p[$i - 2], $p[$i - 1]); $this->_outLine($p[$i], $p[$i + 1]); $this->_out('S'); $this->_outPoint($p[$i], $p[$i + 1]); } else { $this->_outLine($p[$i], $p[$i + 1]); } } } else { $this->_outLine($p[$i], $p[$i + 1]); } } $this->_out($op); } } if ($draw) { $this->_outPoint($p[0], $p[1]); for ($i = 2; $i < $nc; $i = $i + 2) { $this->_outLine($p[$i], $p[$i + 1]); } $this->_out($op); } } /** * Draws a regular polygon. * @param float $x0 Abscissa of center point. * @param float $y0 Ordinate of center point. * @param float $r: Radius of inscribed circle. * @param integer $ns Number of sides. * @param float $angle Angle oriented (anti-clockwise). Default value: 0. * @param boolean $draw_circle Draw inscribed circle or not. Default value: false. * @param string $style Style of rendering. See the getPathPaintOperator() function for more information. * @param array $line_style Line style of polygon sides. Array with keys among the following: * <ul> * <li>all: Line style of all sides. Array like for {@link SetLineStyle SetLineStyle}.</li> * <li>0 to ($ns - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li> * </ul> * If a key is not present or is null, not draws the side. Default value is default line style (empty array). * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array). * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are: * <ul> * <li>D or empty string: Draw (default).</li> * <li>F: Fill.</li> * <li>DF or FD: Draw and fill.</li> * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li> * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li> * </ul> * @param array $circle_outLine_style Line style of inscribed circle (if draws). Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array). * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array). * @access public * @since 2.1.000 (2008-01-08) */ public function RegularPolygon($x0, $y0, $r, $ns, $angle=0, $draw_circle=false, $style='', $line_style=array(), $fill_color=array(), $circle_style='', $circle_outLine_style=array(), $circle_fill_color=array()) { if (3 > $ns) { $ns = 3; } if ($draw_circle) { $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color); } $p = array(); for ($i = 0; $i < $ns; ++$i) { $a = $angle + ($i * 360 / $ns); $a_rad = deg2rad((float) $a); $p[] = $x0 + ($r * sin($a_rad)); $p[] = $y0 + ($r * cos($a_rad)); } $this->Polygon($p, $style, $line_style, $fill_color); } /** * Draws a star polygon * @param float $x0 Abscissa of center point. * @param float $y0 Ordinate of center point. * @param float $r Radius of inscribed circle. * @param integer $nv Number of vertices. * @param integer $ng Number of gap (if ($ng % $nv = 1) then is a regular polygon). * @param float $angle: Angle oriented (anti-clockwise). Default value: 0. * @param boolean $draw_circle: Draw inscribed circle or not. Default value is false. * @param string $style Style of rendering. See the getPathPaintOperator() function for more information. * @param array $line_style Line style of polygon sides. Array with keys among the following: * <ul> * <li>all: Line style of all sides. Array like for * {@link SetLineStyle SetLineStyle}.</li> * <li>0 to (n - 1): Line style of each side. Array like for {@link SetLineStyle SetLineStyle}.</li> * </ul> * If a key is not present or is null, not draws the side. Default value is default line style (empty array). * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array). * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are: * <ul> * <li>D or empty string: Draw (default).</li> * <li>F: Fill.</li> * <li>DF or FD: Draw and fill.</li> * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li> * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li> * </ul> * @param array $circle_outLine_style Line style of inscribed circle (if draws). Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array). * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array). * @access public * @since 2.1.000 (2008-01-08) */ public function StarPolygon($x0, $y0, $r, $nv, $ng, $angle=0, $draw_circle=false, $style='', $line_style=array(), $fill_color=array(), $circle_style='', $circle_outLine_style=array(), $circle_fill_color=array()) { if ($nv < 2) { $nv = 2; } if ($draw_circle) { $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color); } $p2 = array(); $visited = array(); for ($i = 0; $i < $nv; ++$i) { $a = $angle + ($i * 360 / $nv); $a_rad = deg2rad((float) $a); $p2[] = $x0 + ($r * sin($a_rad)); $p2[] = $y0 + ($r * cos($a_rad)); $visited[] = false; } $p = array(); $i = 0; do { $p[] = $p2[$i * 2]; $p[] = $p2[($i * 2) + 1]; $visited[$i] = true; $i += $ng; $i %= $nv; } while (!$visited[$i]); $this->Polygon($p, $style, $line_style, $fill_color); } /** * Draws a rounded rectangle. * @param float $x Abscissa of upper-left corner. * @param float $y Ordinate of upper-left corner. * @param float $w Width. * @param float $h Height. * @param float $r the radius of the circle used to round off the corners of the rectangle. * @param string $round_corner Draws rounded corner or not. String with a 0 (not rounded i-corner) or 1 (rounded i-corner) in i-position. Positions are, in order and begin to 0: top left, top right, bottom right and bottom left. Default value: all rounded corner ("1111"). * @param string $style Style of rendering. See the getPathPaintOperator() function for more information. * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array). * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array). * @access public * @since 2.1.000 (2008-01-08) */ public function RoundedRect($x, $y, $w, $h, $r, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) { $this->RoundedRectXY($x, $y, $w, $h, $r, $r, $round_corner, $style, $border_style, $fill_color); } /** * Draws a rounded rectangle. * @param float $x Abscissa of upper-left corner. * @param float $y Ordinate of upper-left corner. * @param float $w Width. * @param float $h Height. * @param float $rx the x-axis radius of the ellipse used to round off the corners of the rectangle. * @param float $ry the y-axis radius of the ellipse used to round off the corners of the rectangle. * @param string $round_corner Draws rounded corner or not. String with a 0 (not rounded i-corner) or 1 (rounded i-corner) in i-position. Positions are, in order and begin to 0: top left, top right, bottom right and bottom left. Default value: all rounded corner ("1111"). * @param string $style Style of rendering. See the getPathPaintOperator() function for more information. * @param array $border_style Border style of rectangle. Array like for {@link SetLineStyle SetLineStyle}. Default value: default line style (empty array). * @param array $fill_color Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array). * @access public * @since 4.9.019 (2010-04-22) */ public function RoundedRectXY($x, $y, $w, $h, $rx, $ry, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) { if (($round_corner == '0000') OR (($rx == $ry) AND ($rx == 0))) { // Not rounded $this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color); return; } // Rounded if (!(false === strpos($style, 'F')) AND isset($fill_color)) { $this->SetFillColorArray($fill_color); } $op = $this->getPathPaintOperator($style); if ($op == 'f') { $border_style = array(); } if ($border_style) { $this->SetLineStyle($border_style); } $MyArc = 4 / 3 * (sqrt(2) - 1); $this->_outPoint($x + $rx, $y); $xc = $x + $w - $rx; $yc = $y + $ry; $this->_outLine($xc, $y); if ($round_corner[0]) { $this->_outCurve($xc + ($rx * $MyArc), $yc - $ry, $xc + $rx, $yc - ($ry * $MyArc), $xc + $rx, $yc); } else { $this->_outLine($x + $w, $y); } $xc = $x + $w - $rx; $yc = $y + $h - $ry; $this->_outLine($x + $w, $yc); if ($round_corner[1]) { $this->_outCurve($xc + $rx, $yc + ($ry * $MyArc), $xc + ($rx * $MyArc), $yc + $ry, $xc, $yc + $ry); } else { $this->_outLine($x + $w, $y + $h); } $xc = $x + $rx; $yc = $y + $h - $ry; $this->_outLine($xc, $y + $h); if ($round_corner[2]) { $this->_outCurve($xc - ($rx * $MyArc), $yc + $ry, $xc - $rx, $yc + ($ry * $MyArc), $xc - $rx, $yc); } else { $this->_outLine($x, $y + $h); } $xc = $x + $rx; $yc = $y + $ry; $this->_outLine($x, $yc); if ($round_corner[3]) { $this->_outCurve($xc - $rx, $yc - ($ry * $MyArc), $xc - ($rx * $MyArc), $yc - $ry, $xc, $yc - $ry); } else { $this->_outLine($x, $y); $this->_outLine($x + $rx, $y); } $this->_out($op); } /** * Draws a grahic arrow. * @param float $x0 Abscissa of first point. * @param float $y0 Ordinate of first point. * @param float $x0 Abscissa of second point. * @param float $y1 Ordinate of second point. * @param int $head_style (0 = draw only arrowhead arms, 1 = draw closed arrowhead, but no fill, 2 = closed and filled arrowhead, 3 = filled arrowhead) * @param float $arm_size length of arrowhead arms * @param int $arm_angle angle between an arm and the shaft * @author Piotr Galecki, Nicola Asuni, Andy Meier * @since 4.6.018 (2009-07-10) */ public function Arrow($x0, $y0, $x1, $y1, $head_style=0, $arm_size=5, $arm_angle=15) { // getting arrow direction angle // 0 deg angle is when both arms go along X axis. angle grows clockwise. $dir_angle = atan2(($y0 - $y1), ($x0 - $x1)); if ($dir_angle < 0) { $dir_angle += (2 * M_PI); } $arm_angle = deg2rad($arm_angle); $sx1 = $x1; $sy1 = $y1; if ($head_style > 0) { // calculate the stopping point for the arrow shaft $sx1 = $x1 + (($arm_size - $this->LineWidth) * cos($dir_angle)); $sy1 = $y1 + (($arm_size - $this->LineWidth) * sin($dir_angle)); } // main arrow line / shaft $this->Line($x0, $y0, $sx1, $sy1); // left arrowhead arm tip $x2L = $x1 + ($arm_size * cos($dir_angle + $arm_angle)); $y2L = $y1 + ($arm_size * sin($dir_angle + $arm_angle)); // right arrowhead arm tip $x2R = $x1 + ($arm_size * cos($dir_angle - $arm_angle)); $y2R = $y1 + ($arm_size * sin($dir_angle - $arm_angle)); $mode = 'D'; $style = array(); switch ($head_style) { case 0: { // draw only arrowhead arms $mode = 'D'; $style = array(1, 1, 0); break; } case 1: { // draw closed arrowhead, but no fill $mode = 'D'; break; } case 2: { // closed and filled arrowhead $mode = 'DF'; break; } case 3: { // filled arrowhead $mode = 'F'; break; } } $this->Polygon(array($x2L, $y2L, $x1, $y1, $x2R, $y2R), $mode, $style, array()); } // END GRAPHIC FUNCTIONS SECTION ----------------------- // BIDIRECTIONAL TEXT SECTION -------------------------- /** * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/). * @param string $str string to manipulate. * @param bool $setbom if true set the Byte Order Mark (BOM = 0xFEFF) * @param bool $forcertl if true forces RTL text direction * @return string * @access protected * @author Nicola Asuni * @since 2.1.000 (2008-01-08) */ protected function utf8StrRev($str, $setbom=false, $forcertl=false) { return $this->utf8StrArrRev($this->UTF8StringToArray($str), $str, $setbom, $forcertl); } /** * Reverse the RLT substrings array using the Bidirectional Algorithm (http://unicode.org/reports/tr9/). * @param array $arr array of unicode values. * @param string $str string to manipulate (or empty value). * @param bool $setbom if true set the Byte Order Mark (BOM = 0xFEFF) * @param bool $forcertl if true forces RTL text direction * @return string * @access protected * @author Nicola Asuni * @since 4.9.000 (2010-03-27) */ protected function utf8StrArrRev($arr, $str='', $setbom=false, $forcertl=false) { return $this->arrUTF8ToUTF16BE($this->utf8Bidi($arr, $str, $forcertl), $setbom); } /** * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/). * @param array $ta array of characters composing the string. * @param string $str string to process * @param bool $forcertl if 'R' forces RTL, if 'L' forces LTR * @return array of unicode chars * @author Nicola Asuni * @access protected * @since 2.4.000 (2008-03-06) */ protected function utf8Bidi($ta, $str='', $forcertl=false) { global $unicode, $unicode_mirror, $unicode_arlet, $laa_array, $diacritics; // paragraph embedding level $pel = 0; // max level $maxlevel = 0; if ($this->empty_string($str)) { // create string from array $str = $this->UTF8ArrSubString($ta); } // check if string contains arabic text if (preg_match(K_RE_PATTERN_ARABIC, $str)) { $arabic = true; } else { $arabic = false; } // check if string contains RTL text if (!($forcertl OR $arabic OR preg_match(K_RE_PATTERN_RTL, $str))) { return $ta; } // get number of chars $numchars = count($ta); if ($forcertl == 'R') { $pel = 1; } elseif ($forcertl == 'L') { $pel = 0; } else { // P2. In each paragraph, find the first character of type L, AL, or R. // P3. If a character is found in P2 and it is of type AL or R, then set the paragraph embedding level to one; otherwise, set it to zero. for ($i=0; $i < $numchars; ++$i) { $type = $unicode[$ta[$i]]; if ($type == 'L') { $pel = 0; break; } elseif (($type == 'AL') OR ($type == 'R')) { $pel = 1; break; } } } // Current Embedding Level $cel = $pel; // directional override status $dos = 'N'; $remember = array(); // start-of-level-run $sor = $pel % 2 ? 'R' : 'L'; $eor = $sor; // Array of characters data $chardata = Array(); // X1. Begin by setting the current embedding level to the paragraph embedding level. Set the directional override status to neutral. Process each character iteratively, applying rules X2 through X9. Only embedding levels from 0 to 61 are valid in this phase. // In the resolution of levels in rules I1 and I2, the maximum embedding level of 62 can be reached. for ($i=0; $i < $numchars; ++$i) { if ($ta[$i] == K_RLE) { // X2. With each RLE, compute the least greater odd embedding level. // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to neutral. // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status. $next_level = $cel + ($cel % 2) + 1; if ($next_level < 62) { $remember[] = array('num' => K_RLE, 'cel' => $cel, 'dos' => $dos); $cel = $next_level; $dos = 'N'; $sor = $eor; $eor = $cel % 2 ? 'R' : 'L'; } } elseif ($ta[$i] == K_LRE) { // X3. With each LRE, compute the least greater even embedding level. // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to neutral. // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status. $next_level = $cel + 2 - ($cel % 2); if ( $next_level < 62 ) { $remember[] = array('num' => K_LRE, 'cel' => $cel, 'dos' => $dos); $cel = $next_level; $dos = 'N'; $sor = $eor; $eor = $cel % 2 ? 'R' : 'L'; } } elseif ($ta[$i] == K_RLO) { // X4. With each RLO, compute the least greater odd embedding level. // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to right-to-left. // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status. $next_level = $cel + ($cel % 2) + 1; if ($next_level < 62) { $remember[] = array('num' => K_RLO, 'cel' => $cel, 'dos' => $dos); $cel = $next_level; $dos = 'R'; $sor = $eor; $eor = $cel % 2 ? 'R' : 'L'; } } elseif ($ta[$i] == K_LRO) { // X5. With each LRO, compute the least greater even embedding level. // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to left-to-right. // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status. $next_level = $cel + 2 - ($cel % 2); if ( $next_level < 62 ) { $remember[] = array('num' => K_LRO, 'cel' => $cel, 'dos' => $dos); $cel = $next_level; $dos = 'L'; $sor = $eor; $eor = $cel % 2 ? 'R' : 'L'; } } elseif ($ta[$i] == K_PDF) { // X7. With each PDF, determine the matching embedding or override code. If there was a valid matching code, restore (pop) the last remembered (pushed) embedding level and directional override. if (count($remember)) { $last = count($remember ) - 1; if (($remember[$last]['num'] == K_RLE) OR ($remember[$last]['num'] == K_LRE) OR ($remember[$last]['num'] == K_RLO) OR ($remember[$last]['num'] == K_LRO)) { $match = array_pop($remember); $cel = $match['cel']; $dos = $match['dos']; $sor = $eor; $eor = ($cel > $match['cel'] ? $cel : $match['cel']) % 2 ? 'R' : 'L'; } } } elseif (($ta[$i] != K_RLE) AND ($ta[$i] != K_LRE) AND ($ta[$i] != K_RLO) AND ($ta[$i] != K_LRO) AND ($ta[$i] != K_PDF)) { // X6. For all types besides RLE, LRE, RLO, LRO, and PDF: // a. Set the level of the current character to the current embedding level. // b. Whenever the directional override status is not neutral, reset the current character type to the directional override status. if ($dos != 'N') { $chardir = $dos; } else { if (isset($unicode[$ta[$i]])) { $chardir = $unicode[$ta[$i]]; } else { $chardir = 'L'; } } // stores string characters and other information $chardata[] = array('char' => $ta[$i], 'level' => $cel, 'type' => $chardir, 'sor' => $sor, 'eor' => $eor); } } // end for each char // X8. All explicit directional embeddings and overrides are completely terminated at the end of each paragraph. Paragraph separators are not included in the embedding. // X9. Remove all RLE, LRE, RLO, LRO, PDF, and BN codes. // X10. The remaining rules are applied to each run of characters at the same level. For each run, determine the start-of-level-run (sor) and end-of-level-run (eor) type, either L or R. This depends on the higher of the two levels on either side of the boundary (at the start or end of the paragraph, the level of the 'other' run is the base embedding level). If the higher level is odd, the type is R; otherwise, it is L. // 3.3.3 Resolving Weak Types // Weak types are now resolved one level run at a time. At level run boundaries where the type of the character on the other side of the boundary is required, the type assigned to sor or eor is used. // Nonspacing marks are now resolved based on the previous characters. $numchars = count($chardata); // W1. Examine each nonspacing mark (NSM) in the level run, and change the type of the NSM to the type of the previous character. If the NSM is at the start of the level run, it will get the type of sor. $prevlevel = -1; // track level changes $levcount = 0; // counts consecutive chars at the same level for ($i=0; $i < $numchars; ++$i) { if ($chardata[$i]['type'] == 'NSM') { if ($levcount) { $chardata[$i]['type'] = $chardata[$i]['sor']; } elseif ($i > 0) { $chardata[$i]['type'] = $chardata[($i-1)]['type']; } } if ($chardata[$i]['level'] != $prevlevel) { $levcount = 0; } else { ++$levcount; } $prevlevel = $chardata[$i]['level']; } // W2. Search backward from each instance of a European number until the first strong type (R, L, AL, or sor) is found. If an AL is found, change the type of the European number to Arabic number. $prevlevel = -1; $levcount = 0; for ($i=0; $i < $numchars; ++$i) { if ($chardata[$i]['char'] == 'EN') { for ($j=$levcount; $j >= 0; $j--) { if ($chardata[$j]['type'] == 'AL') { $chardata[$i]['type'] = 'AN'; } elseif (($chardata[$j]['type'] == 'L') OR ($chardata[$j]['type'] == 'R')) { break; } } } if ($chardata[$i]['level'] != $prevlevel) { $levcount = 0; } else { ++$levcount; } $prevlevel = $chardata[$i]['level']; } // W3. Change all ALs to R. for ($i=0; $i < $numchars; ++$i) { if ($chardata[$i]['type'] == 'AL') { $chardata[$i]['type'] = 'R'; } } // W4. A single European separator between two European numbers changes to a European number. A single common separator between two numbers of the same type changes to that type. $prevlevel = -1; $levcount = 0; for ($i=0; $i < $numchars; ++$i) { if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) { if (($chardata[$i]['type'] == 'ES') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) { $chardata[$i]['type'] = 'EN'; } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) { $chardata[$i]['type'] = 'EN'; } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'AN') AND ($chardata[($i+1)]['type'] == 'AN')) { $chardata[$i]['type'] = 'AN'; } } if ($chardata[$i]['level'] != $prevlevel) { $levcount = 0; } else { ++$levcount; } $prevlevel = $chardata[$i]['level']; } // W5. A sequence of European terminators adjacent to European numbers changes to all European numbers. $prevlevel = -1; $levcount = 0; for ($i=0; $i < $numchars; ++$i) { if ($chardata[$i]['type'] == 'ET') { if (($levcount > 0) AND ($chardata[($i-1)]['type'] == 'EN')) { $chardata[$i]['type'] = 'EN'; } else { $j = $i+1; while (($j < $numchars) AND ($chardata[$j]['level'] == $prevlevel)) { if ($chardata[$j]['type'] == 'EN') { $chardata[$i]['type'] = 'EN'; break; } elseif ($chardata[$j]['type'] != 'ET') { break; } ++$j; } } } if ($chardata[$i]['level'] != $prevlevel) { $levcount = 0; } else { ++$levcount; } $prevlevel = $chardata[$i]['level']; } // W6. Otherwise, separators and terminators change to Other Neutral. $prevlevel = -1; $levcount = 0; for ($i=0; $i < $numchars; ++$i) { if (($chardata[$i]['type'] == 'ET') OR ($chardata[$i]['type'] == 'ES') OR ($chardata[$i]['type'] == 'CS')) { $chardata[$i]['type'] = 'ON'; } if ($chardata[$i]['level'] != $prevlevel) { $levcount = 0; } else { ++$levcount; } $prevlevel = $chardata[$i]['level']; } //W7. Search backward from each instance of a European number until the first strong type (R, L, or sor) is found. If an L is found, then change the type of the European number to L. $prevlevel = -1; $levcount = 0; for ($i=0; $i < $numchars; ++$i) { if ($chardata[$i]['char'] == 'EN') { for ($j=$levcount; $j >= 0; $j--) { if ($chardata[$j]['type'] == 'L') { $chardata[$i]['type'] = 'L'; } elseif ($chardata[$j]['type'] == 'R') { break; } } } if ($chardata[$i]['level'] != $prevlevel) { $levcount = 0; } else { ++$levcount; } $prevlevel = $chardata[$i]['level']; } // N1. A sequence of neutrals takes the direction of the surrounding strong text if the text on both sides has the same direction. European and Arabic numbers act as if they were R in terms of their influence on neutrals. Start-of-level-run (sor) and end-of-level-run (eor) are used at level run boundaries. $prevlevel = -1; $levcount = 0; for ($i=0; $i < $numchars; ++$i) { if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) { if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) { $chardata[$i]['type'] = 'L'; } elseif (($chardata[$i]['type'] == 'N') AND (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) { $chardata[$i]['type'] = 'R'; } elseif ($chardata[$i]['type'] == 'N') { // N2. Any remaining neutrals take the embedding direction $chardata[$i]['type'] = $chardata[$i]['sor']; } } elseif (($levcount == 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) { // first char if (($chardata[$i]['type'] == 'N') AND ($chardata[$i]['sor'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) { $chardata[$i]['type'] = 'L'; } elseif (($chardata[$i]['type'] == 'N') AND (($chardata[$i]['sor'] == 'R') OR ($chardata[$i]['sor'] == 'EN') OR ($chardata[$i]['sor'] == 'AN')) AND (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) { $chardata[$i]['type'] = 'R'; } elseif ($chardata[$i]['type'] == 'N') { // N2. Any remaining neutrals take the embedding direction $chardata[$i]['type'] = $chardata[$i]['sor']; } } elseif (($levcount > 0) AND ((($i+1) == $numchars) OR (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] != $prevlevel))) { //last char if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[$i]['eor'] == 'L')) { $chardata[$i]['type'] = 'L'; } elseif (($chardata[$i]['type'] == 'N') AND (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND (($chardata[$i]['eor'] == 'R') OR ($chardata[$i]['eor'] == 'EN') OR ($chardata[$i]['eor'] == 'AN'))) { $chardata[$i]['type'] = 'R'; } elseif ($chardata[$i]['type'] == 'N') { // N2. Any remaining neutrals take the embedding direction $chardata[$i]['type'] = $chardata[$i]['sor']; } } elseif ($chardata[$i]['type'] == 'N') { // N2. Any remaining neutrals take the embedding direction $chardata[$i]['type'] = $chardata[$i]['sor']; } if ($chardata[$i]['level'] != $prevlevel) { $levcount = 0; } else { ++$levcount; } $prevlevel = $chardata[$i]['level']; } // I1. For all characters with an even (left-to-right) embedding direction, those of type R go up one level and those of type AN or EN go up two levels. // I2. For all characters with an odd (right-to-left) embedding direction, those of type L, EN or AN go up one level. for ($i=0; $i < $numchars; ++$i) { $odd = $chardata[$i]['level'] % 2; if ($odd) { if (($chardata[$i]['type'] == 'L') OR ($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')) { $chardata[$i]['level'] += 1; } } else { if ($chardata[$i]['type'] == 'R') { $chardata[$i]['level'] += 1; } elseif (($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')) { $chardata[$i]['level'] += 2; } } $maxlevel = max($chardata[$i]['level'],$maxlevel); } // L1. On each line, reset the embedding level of the following characters to the paragraph embedding level: // 1. Segment separators, // 2. Paragraph separators, // 3. Any sequence of whitespace characters preceding a segment separator or paragraph separator, and // 4. Any sequence of white space characters at the end of the line. for ($i=0; $i < $numchars; ++$i) { if (($chardata[$i]['type'] == 'B') OR ($chardata[$i]['type'] == 'S')) { $chardata[$i]['level'] = $pel; } elseif ($chardata[$i]['type'] == 'WS') { $j = $i+1; while ($j < $numchars) { if ((($chardata[$j]['type'] == 'B') OR ($chardata[$j]['type'] == 'S')) OR (($j == ($numchars-1)) AND ($chardata[$j]['type'] == 'WS'))) { $chardata[$i]['level'] = $pel; break; } elseif ($chardata[$j]['type'] != 'WS') { break; } ++$j; } } } // Arabic Shaping // Cursively connected scripts, such as Arabic or Syriac, require the selection of positional character shapes that depend on adjacent characters. Shaping is logically applied after the Bidirectional Algorithm is used and is limited to characters within the same directional run. if ($arabic) { $endedletter = array(1569,1570,1571,1572,1573,1575,1577,1583,1584,1585,1586,1608,1688); $alfletter = array(1570,1571,1573,1575); $chardata2 = $chardata; $laaletter = false; $charAL = array(); $x = 0; for ($i=0; $i < $numchars; ++$i) { if (($unicode[$chardata[$i]['char']] == 'AL') OR ($chardata[$i]['char'] == 32) OR ($chardata[$i]['char'] == 8204)) { $charAL[$x] = $chardata[$i]; $charAL[$x]['i'] = $i; $chardata[$i]['x'] = $x; ++$x; } } $numAL = $x; for ($i=0; $i < $numchars; ++$i) { $thischar = $chardata[$i]; if ($i > 0) { $prevchar = $chardata[($i-1)]; } else { $prevchar = false; } if (($i+1) < $numchars) { $nextchar = $chardata[($i+1)]; } else { $nextchar = false; } if ($unicode[$thischar['char']] == 'AL') { $x = $thischar['x']; if ($x > 0) { $prevchar = $charAL[($x-1)]; } else { $prevchar = false; } if (($x+1) < $numAL) { $nextchar = $charAL[($x+1)]; } else { $nextchar = false; } // if laa letter if (($prevchar !== false) AND ($prevchar['char'] == 1604) AND (in_array($thischar['char'], $alfletter))) { $arabicarr = $laa_array; $laaletter = true; if ($x > 1) { $prevchar = $charAL[($x-2)]; } else { $prevchar = false; } } else { $arabicarr = $unicode_arlet; $laaletter = false; } if (($prevchar !== false) AND ($nextchar !== false) AND (($unicode[$prevchar['char']] == 'AL') OR ($unicode[$prevchar['char']] == 'NSM')) AND (($unicode[$nextchar['char']] == 'AL') OR ($unicode[$nextchar['char']] == 'NSM')) AND ($prevchar['type'] == $thischar['type']) AND ($nextchar['type'] == $thischar['type']) AND ($nextchar['char'] != 1567)) { if (in_array($prevchar['char'], $endedletter)) { if (isset($arabicarr[$thischar['char']][2])) { // initial $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2]; } } else { if (isset($arabicarr[$thischar['char']][3])) { // medial $chardata2[$i]['char'] = $arabicarr[$thischar['char']][3]; } } } elseif (($nextchar !== false) AND (($unicode[$nextchar['char']] == 'AL') OR ($unicode[$nextchar['char']] == 'NSM')) AND ($nextchar['type'] == $thischar['type']) AND ($nextchar['char'] != 1567)) { if (isset($arabicarr[$chardata[$i]['char']][2])) { // initial $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2]; } } elseif ((($prevchar !== false) AND (($unicode[$prevchar['char']] == 'AL') OR ($unicode[$prevchar['char']] == 'NSM')) AND ($prevchar['type'] == $thischar['type'])) OR (($nextchar !== false) AND ($nextchar['char'] == 1567))) { // final if (($i > 1) AND ($thischar['char'] == 1607) AND ($chardata[$i-1]['char'] == 1604) AND ($chardata[$i-2]['char'] == 1604)) { //Allah Word // mark characters to delete with false $chardata2[$i-2]['char'] = false; $chardata2[$i-1]['char'] = false; $chardata2[$i]['char'] = 65010; } else { if (($prevchar !== false) AND in_array($prevchar['char'], $endedletter)) { if (isset($arabicarr[$thischar['char']][0])) { // isolated $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0]; } } else { if (isset($arabicarr[$thischar['char']][1])) { // final $chardata2[$i]['char'] = $arabicarr[$thischar['char']][1]; } } } } elseif (isset($arabicarr[$thischar['char']][0])) { // isolated $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0]; } // if laa letter if ($laaletter) { // mark characters to delete with false $chardata2[($charAL[($x-1)]['i'])]['char'] = false; } } // end if AL (Arabic Letter) } // end for each char /* * Combining characters that can occur with Arabic Shadda (0651 HEX, 1617 DEC) are replaced. * Putting the combining mark and shadda in the same glyph allows us to avoid the two marks overlapping each other in an illegible manner. */ $cw = &$this->CurrentFont['cw']; for ($i = 0; $i < ($numchars-1); ++$i) { if (($chardata2[$i]['char'] == 1617) AND (isset($diacritics[($chardata2[$i+1]['char'])]))) { // check if the subtitution font is defined on current font if (isset($cw[($diacritics[($chardata2[$i+1]['char'])])])) { $chardata2[$i]['char'] = false; $chardata2[$i+1]['char'] = $diacritics[($chardata2[$i+1]['char'])]; } } } // remove marked characters foreach ($chardata2 as $key => $value) { if ($value['char'] === false) { unset($chardata2[$key]); } } $chardata = array_values($chardata2); $numchars = count($chardata); unset($chardata2); unset($arabicarr); unset($laaletter); unset($charAL); } // L2. From the highest level found in the text to the lowest odd level on each line, including intermediate levels not actually present in the text, reverse any contiguous sequence of characters that are at that level or higher. for ($j=$maxlevel; $j > 0; $j--) { $ordarray = Array(); $revarr = Array(); $onlevel = false; for ($i=0; $i < $numchars; ++$i) { if ($chardata[$i]['level'] >= $j) { $onlevel = true; if (isset($unicode_mirror[$chardata[$i]['char']])) { // L4. A character is depicted by a mirrored glyph if and only if (a) the resolved directionality of that character is R, and (b) the Bidi_Mirrored property value of that character is true. $chardata[$i]['char'] = $unicode_mirror[$chardata[$i]['char']]; } $revarr[] = $chardata[$i]; } else { if ($onlevel) { $revarr = array_reverse($revarr); $ordarray = array_merge($ordarray, $revarr); $revarr = Array(); $onlevel = false; } $ordarray[] = $chardata[$i]; } } if ($onlevel) { $revarr = array_reverse($revarr); $ordarray = array_merge($ordarray, $revarr); } $chardata = $ordarray; } $ordarray = array(); for ($i=0; $i < $numchars; ++$i) { $ordarray[] = $chardata[$i]['char']; // store char values for subsetting $this->CurrentFont['subsetchars'][$chardata[$i]['char']] = true; } // update font subsetchars $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']); return $ordarray; } // END OF BIDIRECTIONAL TEXT SECTION ------------------- /** * Adds a bookmark. * @param string $txt bookmark description. * @param int $level bookmark level (minimum value is 0). * @param float $y Y position in user units of the bookmark on the selected page (default = -1 = current position; 0 = page start;). * @param int $page target page number (leave empty for current page). * @access public * @author Olivier Plathey, Nicola Asuni * @since 2.1.002 (2008-02-12) */ public function Bookmark($txt, $level=0, $y=-1, $page='') { if ($level < 0) { $level = 0; } if (isset($this->outlines[0])) { $lastoutline = end($this->outlines); $maxlevel = $lastoutline['l'] + 1; } else { $maxlevel = 0; } if ($level > $maxlevel) { $level = $maxlevel; } if ($y == -1) { $y = $this->GetY(); } if (empty($page)) { $page = $this->PageNo(); if (empty($page)) { return; } } $this->outlines[] = array('t' => $txt, 'l' => $level, 'y' => $y, 'p' => $page); } /** * Create a bookmark PDF string. * @access protected * @author Olivier Plathey, Nicola Asuni * @since 2.1.002 (2008-02-12) */ protected function _putbookmarks() { $nb = count($this->outlines); if ($nb == 0) { return; } // get sorting columns $outline_p = array(); $outline_y = array(); foreach ($this->outlines as $key => $row) { $outline_p[$key] = $row['p']; $outline_k[$key] = $key; } // sort outlines by page and original position array_multisort($outline_p, SORT_NUMERIC, SORT_ASC, $outline_k, SORT_NUMERIC, SORT_ASC, $this->outlines); $lru = array(); $level = 0; foreach ($this->outlines as $i => $o) { if ($o['l'] > 0) { $parent = $lru[($o['l'] - 1)]; //Set parent and last pointers $this->outlines[$i]['parent'] = $parent; $this->outlines[$parent]['last'] = $i; if ($o['l'] > $level) { //Level increasing: set first pointer $this->outlines[$parent]['first'] = $i; } } else { $this->outlines[$i]['parent'] = $nb; } if (($o['l'] <= $level) AND ($i > 0)) { //Set prev and next pointers $prev = $lru[$o['l']]; $this->outlines[$prev]['next'] = $i; $this->outlines[$i]['prev'] = $prev; } $lru[$o['l']] = $i; $level = $o['l']; } //Outline items $n = $this->n + 1; $nltags = '/<br[\s]?\/>|<\/(blockquote|dd|dl|div|dt|h1|h2|h3|h4|h5|h6|hr|li|ol|p|pre|ul|tcpdf|table|tr|td)>/si'; foreach ($this->outlines as $i => $o) { if (isset($this->page_obj_id[($o['p'])])) { $oid = $this->_newobj(); // covert HTML title to string $title = preg_replace($nltags, "\n", $o['t']); $title = preg_replace("/[\r]+/si", '', $title); $title = preg_replace("/[\n]+/si", "\n", $title); $title = strip_tags($title); $title = $this->stringTrim($title); $out = '<</Title '.$this->_textstring($title, $oid); $out .= ' /Parent '.($n + $o['parent']).' 0 R'; if (isset($o['prev'])) { $out .= ' /Prev '.($n + $o['prev']).' 0 R'; } if (isset($o['next'])) { $out .= ' /Next '.($n + $o['next']).' 0 R'; } if (isset($o['first'])) { $out .= ' /First '.($n + $o['first']).' 0 R'; } if (isset($o['last'])) { $out .= ' /Last '.($n + $o['last']).' 0 R'; } $out .= ' '.sprintf('/Dest [%u 0 R /XYZ 0 %.2F null]', $this->page_obj_id[($o['p'])], ($this->pagedim[$o['p']]['h'] - ($o['y'] * $this->k))); $out .= ' /Count 0 >>'; $out .= "\n".'endobj'; $this->_out($out); } } //Outline root $this->OutlineRoot = $this->_newobj(); $this->_out('<< /Type /Outlines /First '.$n.' 0 R /Last '.($n + $lru[0]).' 0 R >>'."\n".'endobj'); } // --- JAVASCRIPT ------------------------------------------------------ /** * Adds a javascript * @param string $script Javascript code * @access public * @author Johannes Güntert, Nicola Asuni * @since 2.1.002 (2008-02-12) */ public function IncludeJS($script) { $this->javascript .= $script; } /** * Adds a javascript object and return object ID * @param string $script Javascript code * @param boolean $onload if true executes this object when opening the document * @return int internal object ID * @access public * @author Nicola Asuni * @since 4.8.000 (2009-09-07) */ public function addJavascriptObject($script, $onload=false) { ++$this->n; $this->js_objects[$this->n] = array('n' => $this->n, 'js' => $script, 'onload' => $onload); return $this->n; } /** * Create a javascript PDF string. * @access protected * @author Johannes Güntert, Nicola Asuni * @since 2.1.002 (2008-02-12) */ protected function _putjavascript() { if (empty($this->javascript) AND empty($this->js_objects)) { return; } if (strpos($this->javascript, 'this.addField') > 0) { if (!$this->ur['enabled']) { //$this->setUserRights(); } // the following two lines are used to avoid form fields duplication after saving // The addField method only works when releasing user rights (UR3) $jsa = sprintf("ftcpdfdocsaved=this.addField('%s','%s',%d,[%.2F,%.2F,%.2F,%.2F]);", 'tcpdfdocsaved', 'text', 0, 0, 1, 0, 1); $jsb = "getField('tcpdfdocsaved').value='saved';"; $this->javascript = $jsa."\n".$this->javascript."\n".$jsb; } $this->n_js = $this->_newobj(); $out = ' << /Names ['; if (!empty($this->javascript)) { $out .= ' (EmbeddedJS) '.($this->n + 1).' 0 R'; } if (!empty($this->js_objects)) { foreach ($this->js_objects as $key => $val) { if ($val['onload']) { $out .= ' (JS'.$key.') '.$key.' 0 R'; } } } $out .= ' ] >>'; $out .= "\n".'endobj'; $this->_out($out); // default Javascript object if (!empty($this->javascript)) { $obj_id = $this->_newobj(); $out = '<< /S /JavaScript'; $out .= ' /JS '.$this->_textstring($this->javascript, $obj_id); $out .= ' >>'; $out .= "\n".'endobj'; $this->_out($out); } // additional Javascript objects if (!empty($this->js_objects)) { foreach ($this->js_objects as $key => $val) { $out = $this->_getobj($key)."\n".' << /S /JavaScript /JS '.$this->_textstring($val['js'], $key).' >>'."\n".'endobj'; $this->_out($out); } } } /** * Convert color to javascript color. * @param string $color color name or #RRGGBB * @access protected * @author Denis Van Nuffelen, Nicola Asuni * @since 2.1.002 (2008-02-12) */ protected function _JScolor($color) { static $aColors = array('transparent', 'black', 'white', 'red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'dkGray', 'gray', 'ltGray'); if (substr($color,0,1) == '#') { return sprintf("['RGB',%.3F,%.3F,%.3F]", hexdec(substr($color,1,2))/255, hexdec(substr($color,3,2))/255, hexdec(substr($color,5,2))/255); } if (!in_array($color,$aColors)) { $this->Error('Invalid color: '.$color); } return 'color.'.$color; } /** * Adds a javascript form field. * @param string $type field type * @param string $name field name * @param int $x horizontal position * @param int $y vertical position * @param int $w width * @param int $h height * @param array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference. * @access protected * @author Denis Van Nuffelen, Nicola Asuni * @since 2.1.002 (2008-02-12) */ protected function _addfield($type, $name, $x, $y, $w, $h, $prop) { if ($this->rtl) { $x = $x - $w; } // the followind avoid fields duplication after saving the document $this->javascript .= "if(getField('tcpdfdocsaved').value != 'saved') {"; $k = $this->k; $this->javascript .= sprintf("f".$name."=this.addField('%s','%s',%u,[%.2F,%.2F,%.2F,%.2F]);", $name, $type, $this->PageNo()-1, $x*$k, ($this->h-$y)*$k+1, ($x+$w)*$k, ($this->h-$y-$h)*$k+1)."\n"; $this->javascript .= 'f'.$name.'.textSize='.$this->FontSizePt.";\n"; while (list($key, $val) = each($prop)) { if (strcmp(substr($key, -5), 'Color') == 0) { $val = $this->_JScolor($val); } else { $val = "'".$val."'"; } $this->javascript .= 'f'.$name.'.'.$key.'='.$val.";\n"; } if ($this->rtl) { $this->x -= $w; } else { $this->x += $w; } $this->javascript .= '}'; } // --- FORM FIELDS ----------------------------------------------------- /** * Convert JavaScript form fields properties array to Annotation Properties array. * @param array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference. * @return array of annotation properties * @access protected * @author Nicola Asuni * @since 4.8.000 (2009-09-06) */ protected function getAnnotOptFromJSProp($prop) { if (isset($prop['aopt']) AND is_array($prop['aopt'])) { // the annotation options area lready defined return $prop['aopt']; } $opt = array(); // value to be returned // alignment: Controls how the text is laid out within the text field. if (isset($prop['alignment'])) { switch ($prop['alignment']) { case 'left': { $opt['q'] = 0; break; } case 'center': { $opt['q'] = 1; break; } case 'right': { $opt['q'] = 2; break; } default: { $opt['q'] = ($this->rtl)?2:0; break; } } } // lineWidth: Specifies the thickness of the border when stroking the perimeter of a field's rectangle. if (isset($prop['lineWidth'])) { $linewidth = intval($prop['lineWidth']); } else { $linewidth = 1; } // borderStyle: The border style for a field. if (isset($prop['borderStyle'])) { switch ($prop['borderStyle']) { case 'border.d': case 'dashed': { $opt['border'] = array(0, 0, $linewidth, array(3, 2)); $opt['bs'] = array('w'=>$linewidth, 's'=>'D', 'd'=>array(3, 2)); break; } case 'border.b': case 'beveled': { $opt['border'] = array(0, 0, $linewidth); $opt['bs'] = array('w'=>$linewidth, 's'=>'B'); break; } case 'border.i': case 'inset': { $opt['border'] = array(0, 0, $linewidth); $opt['bs'] = array('w'=>$linewidth, 's'=>'I'); break; } case 'border.u': case 'underline': { $opt['border'] = array(0, 0, $linewidth); $opt['bs'] = array('w'=>$linewidth, 's'=>'U'); break; } default: case 'border.s': case 'solid': { $opt['border'] = array(0, 0, $linewidth); $opt['bs'] = array('w'=>$linewidth, 's'=>'S'); break; } } } if (isset($prop['border']) AND is_array($prop['border'])) { $opt['border'] = $prop['border']; } if (!isset($opt['mk'])) { $opt['mk'] = array(); } if (!isset($opt['mk']['if'])) { $opt['mk']['if'] = array(); } $opt['mk']['if']['a'] = array(0.5, 0.5); // buttonAlignX: Controls how space is distributed from the left of the button face with respect to the icon. if (isset($prop['buttonAlignX'])) { $opt['mk']['if']['a'][0] = $prop['buttonAlignX']; } // buttonAlignY: Controls how unused space is distributed from the bottom of the button face with respect to the icon. if (isset($prop['buttonAlignY'])) { $opt['mk']['if']['a'][1] = $prop['buttonAlignY']; } // buttonFitBounds: If true, the extent to which the icon may be scaled is set to the bounds of the button field. if (isset($prop['buttonFitBounds']) AND ($prop['buttonFitBounds'] == 'true')) { $opt['mk']['if']['fb'] = true; } // buttonScaleHow: Controls how the icon is scaled (if necessary) to fit inside the button face. if (isset($prop['buttonScaleHow'])) { switch ($prop['buttonScaleHow']) { case 'scaleHow.proportional': { $opt['mk']['if']['s'] = 'P'; break; } case 'scaleHow.anamorphic': { $opt['mk']['if']['s'] = 'A'; break; } } } // buttonScaleWhen: Controls when an icon is scaled to fit inside the button face. if (isset($prop['buttonScaleWhen'])) { switch ($prop['buttonScaleWhen']) { case 'scaleWhen.always': { $opt['mk']['if']['sw'] = 'A'; break; } case 'scaleWhen.never': { $opt['mk']['if']['sw'] = 'N'; break; } case 'scaleWhen.tooBig': { $opt['mk']['if']['sw'] = 'B'; break; } case 'scaleWhen.tooSmall': { $opt['mk']['if']['sw'] = 'S'; break; } } } // buttonPosition: Controls how the text and the icon of the button are positioned with respect to each other within the button face. if (isset($prop['buttonPosition'])) { switch ($prop['buttonPosition']) { case 0: case 'position.textOnly': { $opt['mk']['tp'] = 0; break; } case 1: case 'position.iconOnly': { $opt['mk']['tp'] = 1; break; } case 2: case 'position.iconTextV': { $opt['mk']['tp'] = 2; break; } case 3: case 'position.textIconV': { $opt['mk']['tp'] = 3; break; } case 4: case 'position.iconTextH': { $opt['mk']['tp'] = 4; break; } case 5: case 'position.textIconH': { $opt['mk']['tp'] = 5; break; } case 6: case 'position.overlay': { $opt['mk']['tp'] = 6; break; } } } // fillColor: Specifies the background color for a field. if (isset($prop['fillColor'])) { if (is_array($prop['fillColor'])) { $opt['mk']['bg'] = $prop['fillColor']; } else { $opt['mk']['bg'] = $this->convertHTMLColorToDec($prop['fillColor']); } } // strokeColor: Specifies the stroke color for a field that is used to stroke the rectangle of the field with a line as large as the line width. if (isset($prop['strokeColor'])) { if (is_array($prop['strokeColor'])) { $opt['mk']['bc'] = $prop['strokeColor']; } else { $opt['mk']['bc'] = $this->convertHTMLColorToDec($prop['strokeColor']); } } // rotation: The rotation of a widget in counterclockwise increments. if (isset($prop['rotation'])) { $opt['mk']['r'] = $prop['rotation']; } // charLimit: Limits the number of characters that a user can type into a text field. if (isset($prop['charLimit'])) { $opt['maxlen'] = intval($prop['charLimit']); } if (!isset($ff)) { $ff = 0; } // readonly: The read-only characteristic of a field. If a field is read-only, the user can see the field but cannot change it. if (isset($prop['readonly']) AND ($prop['readonly'] == 'true')) { $ff += 1 << 0; } // required: Specifies whether a field requires a value. if (isset($prop['required']) AND ($prop['required'] == 'true')) { $ff += 1 << 1; } // multiline: Controls how text is wrapped within the field. if (isset($prop['multiline']) AND ($prop['multiline'] == 'true')) { $ff += 1 << 12; } // password: Specifies whether the field should display asterisks when data is entered in the field. if (isset($prop['password']) AND ($prop['password'] == 'true')) { $ff += 1 << 13; } // NoToggleToOff: If set, exactly one radio button shall be selected at all times; selecting the currently selected button has no effect. if (isset($prop['NoToggleToOff']) AND ($prop['NoToggleToOff'] == 'true')) { $ff += 1 << 14; } // Radio: If set, the field is a set of radio buttons. if (isset($prop['Radio']) AND ($prop['Radio'] == 'true')) { $ff += 1 << 15; } // Pushbutton: If set, the field is a pushbutton that does not retain a permanent value. if (isset($prop['Pushbutton']) AND ($prop['Pushbutton'] == 'true')) { $ff += 1 << 16; } // Combo: If set, the field is a combo box; if clear, the field is a list box. if (isset($prop['Combo']) AND ($prop['Combo'] == 'true')) { $ff += 1 << 17; } // editable: Controls whether a combo box is editable. if (isset($prop['editable']) AND ($prop['editable'] == 'true')) { $ff += 1 << 18; } // Sort: If set, the field's option items shall be sorted alphabetically. if (isset($prop['Sort']) AND ($prop['Sort'] == 'true')) { $ff += 1 << 19; } // fileSelect: If true, sets the file-select flag in the Options tab of the text field (Field is Used for File Selection). if (isset($prop['fileSelect']) AND ($prop['fileSelect'] == 'true')) { $ff += 1 << 20; } // multipleSelection: If true, indicates that a list box allows a multiple selection of items. if (isset($prop['multipleSelection']) AND ($prop['multipleSelection'] == 'true')) { $ff += 1 << 21; } // doNotSpellCheck: If true, spell checking is not performed on this editable text field. if (isset($prop['doNotSpellCheck']) AND ($prop['doNotSpellCheck'] == 'true')) { $ff += 1 << 22; } // doNotScroll: If true, the text field does not scroll and the user, therefore, is limited by the rectangular region designed for the field. if (isset($prop['doNotScroll']) AND ($prop['doNotScroll'] == 'true')) { $ff += 1 << 23; } // comb: If set to true, the field background is drawn as series of boxes (one for each character in the value of the field) and each character of the content is drawn within those boxes. The number of boxes drawn is determined from the charLimit property. It applies only to text fields. The setter will also raise if any of the following field properties are also set multiline, password, and fileSelect. A side-effect of setting this property is that the doNotScroll property is also set. if (isset($prop['comb']) AND ($prop['comb'] == 'true')) { $ff += 1 << 24; } // radiosInUnison: If false, even if a group of radio buttons have the same name and export value, they behave in a mutually exclusive fashion, like HTML radio buttons. if (isset($prop['radiosInUnison']) AND ($prop['radiosInUnison'] == 'true')) { $ff += 1 << 25; } // richText: If true, the field allows rich text formatting. if (isset($prop['richText']) AND ($prop['richText'] == 'true')) { $ff += 1 << 25; } // commitOnSelChange: Controls whether a field value is committed after a selection change. if (isset($prop['commitOnSelChange']) AND ($prop['commitOnSelChange'] == 'true')) { $ff += 1 << 26; } $opt['ff'] = $ff; // defaultValue: The default value of a field - that is, the value that the field is set to when the form is reset. if (isset($prop['defaultValue'])) { $opt['dv'] = $prop['defaultValue']; } $f = 4; // default value for annotation flags // readonly: The read-only characteristic of a field. If a field is read-only, the user can see the field but cannot change it. if (isset($prop['readonly']) AND ($prop['readonly'] == 'true')) { $f += 1 << 6; } // display: Controls whether the field is hidden or visible on screen and in print. if (isset($prop['display'])) { if ($prop['display'] == 'display.visible') { // } elseif ($prop['display'] == 'display.hidden') { $f += 1 << 1; } elseif ($prop['display'] == 'display.noPrint') { $f -= 1 << 2; } elseif ($prop['display'] == 'display.noView') { $f += 1 << 5; } } $opt['f'] = $f; // currentValueIndices: Reads and writes single or multiple values of a list box or combo box. if (isset($prop['currentValueIndices']) AND is_array($prop['currentValueIndices'])) { $opt['i'] = $prop['currentValueIndices']; } // value: The value of the field data that the user has entered. if (isset($prop['value'])) { if (is_array($prop['value'])) { $opt['opt'] = array(); foreach ($prop['value'] AS $key => $optval) { // exportValues: An array of strings representing the export values for the field. if (isset($prop['exportValues'][$key])) { $opt['opt'][$key] = array($prop['exportValues'][$key], $prop['value'][$key]); } else { $opt['opt'][$key] = $prop['value'][$key]; } } } else { $opt['v'] = $prop['value']; } } // richValue: This property specifies the text contents and formatting of a rich text field. if (isset($prop['richValue'])) { $opt['rv'] = $prop['richValue']; } // submitName: If nonempty, used during form submission instead of name. Only applicable if submitting in HTML format (that is, URL-encoded). if (isset($prop['submitName'])) { $opt['tm'] = $prop['submitName']; } // name: Fully qualified field name. if (isset($prop['name'])) { $opt['t'] = $prop['name']; } // userName: The user name (short description string) of the field. if (isset($prop['userName'])) { $opt['tu'] = $prop['userName']; } // highlight: Defines how a button reacts when a user clicks it. if (isset($prop['highlight'])) { switch ($prop['highlight']) { case 'none': case 'highlight.n': { $opt['h'] = 'N'; break; } case 'invert': case 'highlight.i': { $opt['h'] = 'i'; break; } case 'push': case 'highlight.p': { $opt['h'] = 'P'; break; } case 'outline': case 'highlight.o': { $opt['h'] = 'O'; break; } } } // Unsupported options: // - calcOrderIndex: Changes the calculation order of fields in the document. // - delay: Delays the redrawing of a field's appearance. // - defaultStyle: This property defines the default style attributes for the form field. // - style: Allows the user to set the glyph style of a check box or radio button. // - textColor, textFont, textSize return $opt; } /** * Set default properties for form fields. * @param array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference. * @access public * @author Nicola Asuni * @since 4.8.000 (2009-09-06) */ public function setFormDefaultProp($prop=array()) { $this->default_form_prop = $prop; } /** * Return the default properties for form fields. * @return array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference. * @access public * @author Nicola Asuni * @since 4.8.000 (2009-09-06) */ public function getFormDefaultProp() { return $this->default_form_prop; } /** * Creates a text field * @param string $name field name * @param float $w Width of the rectangle * @param float $h Height of the rectangle * @param array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference. * @param array $opt annotation parameters. Possible values are described on official PDF32000_2008 reference. * @param float $x Abscissa of the upper-left corner of the rectangle * @param float $y Ordinate of the upper-left corner of the rectangle * @param boolean $js if true put the field using JavaScript (requires Acrobat Writer to be rendered). * @access public * @author Nicola Asuni * @since 4.8.000 (2009-09-07) */ public function TextField($name, $w, $h, $prop=array(), $opt=array(), $x='', $y='', $js=false) { if ($x === '') { $x = $this->x; } if ($y === '') { $y = $this->y; } if ($js) { $this->_addfield('text', $name, $x, $y, $w, $h, $prop); return; } // get default style $prop = array_merge($this->getFormDefaultProp(), $prop); // get annotation data $popt = $this->getAnnotOptFromJSProp($prop); // set default appearance stream $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i']; $fontstyle = sprintf('/F%d %.2F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor); $popt['da'] = $fontstyle; $popt['ap'] = array(); $popt['ap']['n'] = 'q BT '.$fontstyle.' ET Q'; // merge options $opt = array_merge($popt, $opt); // remove some conflicting options unset($opt['bs']); // set remaining annotation data $opt['Subtype'] = 'Widget'; $opt['ft'] = 'Tx'; $opt['t'] = $name; /* Additional annotation's parameters (check _putannotsobj() method): //$opt['f'] //$opt['ap'] //$opt['as'] //$opt['bs'] //$opt['be'] //$opt['c'] //$opt['border'] //$opt['h'] //$opt['mk'] //$opt['mk']['r'] //$opt['mk']['bc'] //$opt['mk']['bg'] //$opt['mk']['ca'] //$opt['mk']['rc'] //$opt['mk']['ac'] //$opt['mk']['i'] //$opt['mk']['ri'] //$opt['mk']['ix'] //$opt['mk']['if'] //$opt['mk']['if']['sw'] //$opt['mk']['if']['s'] //$opt['mk']['if']['a'] //$opt['mk']['if']['fb'] //$opt['mk']['tp'] //$opt['tu'] //$opt['tm'] //$opt['ff'] //$opt['v'] //$opt['dv'] //$opt['a'] //$opt['aa'] //$opt['q'] */ $this->Annotation($x, $y, $w, $h, $name, $opt, 0); if ($this->rtl) { $this->x -= $w; } else { $this->x += $w; } } /** * Creates a RadioButton field * @param string $name field name * @param int $w width * @param array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference. * @param array $opt annotation parameters. Possible values are described on official PDF32000_2008 reference. * @param string $onvalue value to be returned if selected. * @param boolean $checked define the initial state. * @param float $x Abscissa of the upper-left corner of the rectangle * @param float $y Ordinate of the upper-left corner of the rectangle * @param boolean $js if true put the field using JavaScript (requires Acrobat Writer to be rendered). * @access public * @author Nicola Asuni * @since 4.8.000 (2009-09-07) */ public function RadioButton($name, $w, $prop=array(), $opt=array(), $onvalue='On', $checked=false, $x='', $y='', $js=false) { if ($x === '') { $x = $this->x; } if ($y === '') { $y = $this->y; } if ($js) { $this->_addfield('radiobutton', $name, $x, $y, $w, $w, $prop); return; } if ($this->empty_string($onvalue)) { $onvalue = 'On'; } if ($checked) { $defval = $onvalue; } else { $defval = 'Off'; } // set data for parent group if (!isset($this->radiobutton_groups[$this->page])) { $this->radiobutton_groups[$this->page] = array(); } if (!isset($this->radiobutton_groups[$this->page][$name])) { $this->radiobutton_groups[$this->page][$name] = array(); ++$this->n; $this->radiobutton_groups[$this->page][$name]['n'] = $this->n; $this->radio_groups[] = $this->n; $kid = ($this->n + 2); } else { $kid = ($this->n + 1); } // save object ID to be added on Kids entry on parent object $this->radiobutton_groups[$this->page][$name][] = array('kid' => $kid, 'def' => $defval); // get default style $prop = array_merge($this->getFormDefaultProp(), $prop); $prop['NoToggleToOff'] = 'true'; $prop['Radio'] = 'true'; $prop['borderStyle'] = 'inset'; // get annotation data $popt = $this->getAnnotOptFromJSProp($prop); // set additional default values $font = 'zapfdingbats'; $this->AddFont($font); $tmpfont = $this->getFontBuffer($font); $this->annotation_fonts[$tmpfont['fontkey']] = $tmpfont['i']; $fontstyle = sprintf('/F%d %.2F Tf %s', $tmpfont['i'], $this->FontSizePt, $this->TextColor); $popt['da'] = $fontstyle; $popt['ap'] = array(); $popt['ap']['n'] = array(); $popt['ap']['n'][$onvalue] = 'q BT '.$fontstyle.' 0 0 Td (8) Tj ET Q'; $popt['ap']['n']['Off'] = 'q BT '.$fontstyle.' 0 0 Td (8) Tj ET Q'; if (!isset($popt['mk'])) { $popt['mk'] = array(); } $popt['mk']['ca'] = '(l)'; // merge options $opt = array_merge($popt, $opt); // set remaining annotation data $opt['Subtype'] = 'Widget'; $opt['ft'] = 'Btn'; if ($checked) { $opt['v'] = array('/'.$onvalue); $opt['as'] = $onvalue; } else { $opt['as'] = 'Off'; } $this->Annotation($x, $y, $w, $w, $name, $opt, 0); if ($this->rtl) { $this->x -= $w; } else { $this->x += $w; } } /** * Creates a List-box field * @param string $name field name * @param int $w width * @param int $h height * @param array $values array containing the list of values. * @param array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference. * @param array $opt annotation parameters. Possible values are described on official PDF32000_2008 reference. * @param float $x Abscissa of the upper-left corner of the rectangle * @param float $y Ordinate of the upper-left corner of the rectangle * @param boolean $js if true put the field using JavaScript (requires Acrobat Writer to be rendered). * @access public * @author Nicola Asuni * @since 4.8.000 (2009-09-07) */ public function ListBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) { if ($x === '') { $x = $this->x; } if ($y === '') { $y = $this->y; } if ($js) { $this->_addfield('listbox', $name, $x, $y, $w, $h, $prop); $s = ''; foreach ($values as $value) { $s .= "'".addslashes($value)."',"; } $this->javascript .= 'f'.$name.'.setItems(['.substr($s, 0, -1)."]);\n"; return; } // get default style $prop = array_merge($this->getFormDefaultProp(), $prop); // get annotation data $popt = $this->getAnnotOptFromJSProp($prop); // set additional default values $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i']; $fontstyle = sprintf('/F%d %.2F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor); $popt['da'] = $fontstyle; $popt['ap'] = array(); $popt['ap']['n'] = 'q BT '.$fontstyle.' ET Q'; // merge options $opt = array_merge($popt, $opt); // set remaining annotation data $opt['Subtype'] = 'Widget'; $opt['ft'] = 'Ch'; $opt['t'] = $name; $opt['opt'] = $values; $this->Annotation($x, $y, $w, $h, $name, $opt, 0); if ($this->rtl) { $this->x -= $w; } else { $this->x += $w; } } /** * Creates a Combo-box field * @param string $name field name * @param int $w width * @param int $h height * @param array $values array containing the list of values. * @param array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference. * @param array $opt annotation parameters. Possible values are described on official PDF32000_2008 reference. * @param float $x Abscissa of the upper-left corner of the rectangle * @param float $y Ordinate of the upper-left corner of the rectangle * @param boolean $js if true put the field using JavaScript (requires Acrobat Writer to be rendered). * @access public * @author Nicola Asuni * @since 4.8.000 (2009-09-07) */ public function ComboBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) { if ($x === '') { $x = $this->x; } if ($y === '') { $y = $this->y; } if ($js) { $this->_addfield('combobox', $name, $x, $y, $w, $h, $prop); $s = ''; foreach ($values as $value) { $s .= "'".addslashes($value)."',"; } $this->javascript .= 'f'.$name.'.setItems(['.substr($s, 0, -1)."]);\n"; return; } // get default style $prop = array_merge($this->getFormDefaultProp(), $prop); $prop['Combo'] = true; // get annotation data $popt = $this->getAnnotOptFromJSProp($prop); // set additional default options $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i']; $fontstyle = sprintf('/F%d %.2F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor); $popt['da'] = $fontstyle; $popt['ap'] = array(); $popt['ap']['n'] = 'q BT '.$fontstyle.' ET Q'; // merge options $opt = array_merge($popt, $opt); // set remaining annotation data $opt['Subtype'] = 'Widget'; $opt['ft'] = 'Ch'; $opt['t'] = $name; $opt['opt'] = $values; $this->Annotation($x, $y, $w, $h, $name, $opt, 0); if ($this->rtl) { $this->x -= $w; } else { $this->x += $w; } } /** * Creates a CheckBox field * @param string $name field name * @param int $w width * @param boolean $checked define the initial state. * @param array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference. * @param array $opt annotation parameters. Possible values are described on official PDF32000_2008 reference. * @param string $onvalue value to be returned if selected. * @param float $x Abscissa of the upper-left corner of the rectangle * @param float $y Ordinate of the upper-left corner of the rectangle * @param boolean $js if true put the field using JavaScript (requires Acrobat Writer to be rendered). * @access public * @author Nicola Asuni * @since 4.8.000 (2009-09-07) */ public function CheckBox($name, $w, $checked=false, $prop=array(), $opt=array(), $onvalue='Yes', $x='', $y='', $js=false) { if ($x === '') { $x = $this->x; } if ($y === '') { $y = $this->y; } if ($js) { $this->_addfield('checkbox', $name, $x, $y, $w, $w, $prop); return; } if (!isset($prop['value'])) { $prop['value'] = array('Yes'); } // get default style $prop = array_merge($this->getFormDefaultProp(), $prop); $prop['borderStyle'] = 'inset'; // get annotation data $popt = $this->getAnnotOptFromJSProp($prop); // set additional default options $font = 'zapfdingbats'; $this->AddFont($font); $tmpfont = $this->getFontBuffer($font); $this->annotation_fonts[$tmpfont['fontkey']] = $tmpfont['i']; $fontstyle = sprintf('/F%d %.2F Tf %s', $tmpfont['i'], $this->FontSizePt, $this->TextColor); $popt['da'] = $fontstyle; $popt['ap'] = array(); $popt['ap']['n'] = array(); $popt['ap']['n']['Yes'] = 'q BT '.$fontstyle.' 0 0 Td (8) Tj ET Q'; $popt['ap']['n']['Off'] = 'q BT '.$fontstyle.' 0 0 Td (8) Tj ET Q'; // merge options $opt = array_merge($popt, $opt); // set remaining annotation data $opt['Subtype'] = 'Widget'; $opt['ft'] = 'Btn'; $opt['t'] = $name; $opt['opt'] = array($onvalue); if ($checked) { $opt['v'] = array('/0'); $opt['as'] = 'Yes'; } else { $opt['v'] = array('/Off'); $opt['as'] = 'Off'; } $this->Annotation($x, $y, $w, $w, $name, $opt, 0); if ($this->rtl) { $this->x -= $w; } else { $this->x += $w; } } /** * Creates a button field * @param string $name field name * @param int $w width * @param int $h height * @param string $caption caption. * @param mixed $action action triggered by pressing the button. Use a string to specify a javascript action. Use an array to specify a form action options as on section 12.7.5 of PDF32000_2008. * @param array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference. * @param array $opt annotation parameters. Possible values are described on official PDF32000_2008 reference. * @param float $x Abscissa of the upper-left corner of the rectangle * @param float $y Ordinate of the upper-left corner of the rectangle * @param boolean $js if true put the field using JavaScript (requires Acrobat Writer to be rendered). * @access public * @author Nicola Asuni * @since 4.8.000 (2009-09-07) */ public function Button($name, $w, $h, $caption, $action, $prop=array(), $opt=array(), $x='', $y='', $js=false) { if ($x === '') { $x = $this->x; } if ($y === '') { $y = $this->y; } if ($js) { $this->_addfield('button', $name, $this->x, $this->y, $w, $h, $prop); $this->javascript .= 'f'.$name.".buttonSetCaption('".addslashes($caption)."');\n"; $this->javascript .= 'f'.$name.".setAction('MouseUp','".addslashes($action)."');\n"; $this->javascript .= 'f'.$name.".highlight='push';\n"; $this->javascript .= 'f'.$name.".print=false;\n"; return; } // get default style $prop = array_merge($this->getFormDefaultProp(), $prop); $prop['Pushbutton'] = 'true'; $prop['highlight'] = 'push'; $prop['display'] = 'display.noPrint'; // get annotation data $popt = $this->getAnnotOptFromJSProp($prop); $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i']; $fontstyle = sprintf('/F%d %.2F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor); $popt['da'] = $fontstyle; $popt['ap'] = array(); $popt['ap']['n'] = 'q BT '.$fontstyle.' ET Q'; // set additional default options if (!isset($popt['mk'])) { $popt['mk'] = array(); } $ann_obj_id = ($this->n + 1); if (!empty($action) AND !is_array($action)) { $ann_obj_id = ($this->n + 2); } $popt['mk']['ca'] = $this->_textstring($caption, $ann_obj_id); $popt['mk']['rc'] = $this->_textstring($caption, $ann_obj_id); $popt['mk']['ac'] = $this->_textstring($caption, $ann_obj_id); // merge options $opt = array_merge($popt, $opt); // set remaining annotation data $opt['Subtype'] = 'Widget'; $opt['ft'] = 'Btn'; $opt['t'] = $caption; $opt['v'] = $name; if (!empty($action)) { if (is_array($action)) { // form action options as on section 12.7.5 of PDF32000_2008. $opt['aa'] = '/D <<'; $bmode = array('SubmitForm', 'ResetForm', 'ImportData'); foreach ($action AS $key => $val) { if (($key == 'S') AND in_array($val, $bmode)) { $opt['aa'] .= ' /S /'.$val; } elseif (($key == 'F') AND (!empty($val))) { $opt['aa'] .= ' /F '.$this->_datastring($val, $ann_obj_id); } elseif (($key == 'Fields') AND is_array($val) AND !empty($val)) { $opt['aa'] .= ' /Fields ['; foreach ($val AS $field) { $opt['aa'] .= ' '.$this->_textstring($field, $ann_obj_id); } $opt['aa'] .= ']'; } elseif (($key == 'Flags')) { $ff = 0; if (is_array($val)) { foreach ($val AS $flag) { switch ($flag) { case 'Include/Exclude': { $ff += 1 << 0; break; } case 'IncludeNoValueFields': { $ff += 1 << 1; break; } case 'ExportFormat': { $ff += 1 << 2; break; } case 'GetMethod': { $ff += 1 << 3; break; } case 'SubmitCoordinates': { $ff += 1 << 4; break; } case 'XFDF': { $ff += 1 << 5; break; } case 'IncludeAppendSaves': { $ff += 1 << 6; break; } case 'IncludeAnnotations': { $ff += 1 << 7; break; } case 'SubmitPDF': { $ff += 1 << 8; break; } case 'CanonicalFormat': { $ff += 1 << 9; break; } case 'ExclNonUserAnnots': { $ff += 1 << 10; break; } case 'ExclFKey': { $ff += 1 << 11; break; } case 'EmbedForm': { $ff += 1 << 13; break; } } } } else { $ff = intval($val); } $opt['aa'] .= ' /Flags '.$ff; } } $opt['aa'] .= ' >>'; } else { // Javascript action or raw action command $js_obj_id = $this->addJavascriptObject($action); $opt['aa'] = '/D '.$js_obj_id.' 0 R'; } } $this->Annotation($x, $y, $w, $h, $name, $opt, 0); if ($this->rtl) { $this->x -= $w; } else { $this->x += $w; } } // --- END FORMS FIELDS ------------------------------------------------ /** * Add certification signature (DocMDP or UR3) * You can set only one signature type * @access protected * @author Nicola Asuni * @since 4.6.008 (2009-05-07) */ protected function _putsignature() { if ((!$this->sign) OR (!isset($this->signature_data['cert_type']))) { return; } $out = $this->_getobj($this->sig_obj_id + 1)."\n"; $out .= '<< /Type /Sig'; $out .= ' /Filter /Adobe.PPKLite'; $out .= ' /SubFilter /adbe.pkcs7.detached'; $out .= ' '.$this->byterange_string; $out .= ' /Contents<'.str_repeat('0', $this->signature_max_length).'>'; $out .= ' /Reference ['; // array of signature reference dictionaries $out .= ' << /Type /SigRef'; if ($this->signature_data['cert_type'] > 0) { $out .= ' /TransformMethod /DocMDP'; $out .= ' /TransformParams <<'; $out .= ' /Type /TransformParams'; $out .= ' /V /1.2'; $out .= ' /P '.$this->signature_data['cert_type']; } else { $out .= ' /TransformMethod /UR3'; $out .= ' /TransformParams <<'; $out .= ' /Type /TransformParams'; $out .= ' /V /2.2'; if (!$this->empty_string($this->ur['document'])) { $out .= ' /Document['.$this->ur['document'].']'; } if (!$this->empty_string($this->ur['form'])) { $out .= ' /Form['.$this->ur['form'].']'; } if (!$this->empty_string($this->ur['signature'])) { $out .= ' /Signature['.$this->ur['signature'].']'; } if (!$this->empty_string($this->ur['annots'])) { $out .= ' /Annots['.$this->ur['annots'].']'; } if (!$this->empty_string($this->ur['ef'])) { $out .= ' /EF['.$this->ur['ef'].']'; } if (!$this->empty_string($this->ur['formex'])) { $out .= ' /FormEX['.$this->ur['formex'].']'; } } $out .= ' >>'; // close TransformParams // optional digest data (values must be calculated and replaced later) //$out .= ' /Data ********** 0 R'; //$out .= ' /DigestMethod/MD5'; //$out .= ' /DigestLocation[********** 34]'; //$out .= ' /DigestValue<********************************>'; $out .= ' >>'; $out .= ' ]'; // end of reference if (isset($this->signature_data['info']['Name']) AND !$this->empty_string($this->signature_data['info']['Name'])) { $out .= ' /Name '.$this->_textstring($this->signature_data['info']['Name']); } if (isset($this->signature_data['info']['Location']) AND !$this->empty_string($this->signature_data['info']['Location'])) { $out .= ' /Location '.$this->_textstring($this->signature_data['info']['Location']); } if (isset($this->signature_data['info']['Reason']) AND !$this->empty_string($this->signature_data['info']['Reason'])) { $out .= ' /Reason '.$this->_textstring($this->signature_data['info']['Reason']); } if (isset($this->signature_data['info']['ContactInfo']) AND !$this->empty_string($this->signature_data['info']['ContactInfo'])) { $out .= ' /ContactInfo '.$this->_textstring($this->signature_data['info']['ContactInfo']); } $out .= ' /M '.$this->_datestring(); $out .= ' >>'; $out .= "\n".'endobj'; $this->_out($out); } /** * Set User's Rights for PDF Reader * WARNING: This is experimental and currently do not work. * Check the PDF Reference 8.7.1 Transform Methods, * Table 8.105 Entries in the UR transform parameters dictionary * @param boolean $enable if true enable user's rights on PDF reader * @param string $document Names specifying additional document-wide usage rights for the document. The only defined value is "/FullSave", which permits a user to save the document along with modified form and/or annotation data. * @param string $annots Names specifying additional annotation-related usage rights for the document. Valid names in PDF 1.5 and later are /Create/Delete/Modify/Copy/Import/Export, which permit the user to perform the named operation on annotations. * @param string $form Names specifying additional form-field-related usage rights for the document. Valid names are: /Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate * @param string $signature Names specifying additional signature-related usage rights for the document. The only defined value is /Modify, which permits a user to apply a digital signature to an existing signature form field or clear a signed signature form field. * @param string $ef Names specifying additional usage rights for named embedded files in the document. Valid names are /Create/Delete/Modify/Import, which permit the user to perform the named operation on named embedded files Names specifying additional embedded-files-related usage rights for the document. * @param string $formex Names specifying additional form-field-related usage rights. The only valid name is BarcodePlaintext, which permits text form field data to be encoded as a plaintext two-dimensional barcode. * @access public * @author Nicola Asuni * @since 2.9.000 (2008-03-26) */ public function setUserRights( $enable=true, $document='/FullSave', $annots='/Create/Delete/Modify/Copy/Import/Export', $form='/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate', $signature='/Modify', $ef='/Create/Delete/Modify/Import', $formex='') { $this->ur['enabled'] = $enable; $this->ur['document'] = $document; $this->ur['annots'] = $annots; $this->ur['form'] = $form; $this->ur['signature'] = $signature; $this->ur['ef'] = $ef; $this->ur['formex'] = $formex; if (!$this->sign) { $this->setSignature('', '', '', '', 0, array()); } } /** * Enable document signature (requires the OpenSSL Library). * The digital signature improve document authenticity and integrity and allows o enable extra features on Acrobat Reader. * To create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt * To export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12 * To convert pfx certificate to pem: openssl pkcs12 -in tcpdf.pfx -out tcpdf.crt -nodes * @param mixed $signing_cert signing certificate (string or filename prefixed with 'file://') * @param mixed $private_key private key (string or filename prefixed with 'file://') * @param string $private_key_password password * @param string $extracerts specifies the name of a file containing a bunch of extra certificates to include in the signature which can for example be used to help the recipient to verify the certificate that you used. * @param int $cert_type The access permissions granted for this document. Valid values shall be: 1 = No changes to the document shall be permitted; any change to the document shall invalidate the signature; 2 = Permitted changes shall be filling in forms, instantiating page templates, and signing; other changes shall invalidate the signature; 3 = Permitted changes shall be the same as for 2, as well as annotation creation, deletion, and modification; other changes shall invalidate the signature. * @param array $info array of option information: Name, Location, Reason, ContactInfo. * @access public * @author Nicola Asuni * @since 4.6.005 (2009-04-24) */ public function setSignature($signing_cert='', $private_key='', $private_key_password='', $extracerts='', $cert_type=2, $info=array()) { // to create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt // to export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12 // to convert pfx certificate to pem: openssl // OpenSSL> pkcs12 -in <cert.pfx> -out <cert.crt> -nodes $this->sign = true; ++$this->n; $this->sig_obj_id = $this->n; // signature widget ++$this->n; // signature object ($this->sig_obj_id + 1) $this->signature_data = array(); if (strlen($signing_cert) == 0) { $signing_cert = 'file://'.dirname(__FILE__).'/tcpdf.crt'; $private_key_password = 'tcpdfdemo'; } if (strlen($private_key) == 0) { $private_key = $signing_cert; } $this->signature_data['signcert'] = $signing_cert; $this->signature_data['privkey'] = $private_key; $this->signature_data['password'] = $private_key_password; $this->signature_data['extracerts'] = $extracerts; $this->signature_data['cert_type'] = $cert_type; $this->signature_data['info'] = $info; } /** * Set the digital signature appearance (a cliccable rectangle area to get signature properties) * @param float $x Abscissa of the upper-left corner. * @param float $y Ordinate of the upper-left corner. * @param float $w Width of the signature area. * @param float $h Height of the signature area. * @param int $page option page number (if < 0 the current page is used). * @access public * @author Nicola Asuni * @since 5.3.011 (2010-06-17) */ public function setSignatureAppearance($x=0, $y=0, $w=0, $h=0, $page=-1) { if (($page < 1) OR ($page > $this->numpages)) { $this->signature_appearance['page'] = $this->page; } else { $this->signature_appearance['page'] = intval($page); } $a = $x * $this->k; $b = $this->pagedim[($this->signature_appearance['page'])]['h'] - (($y + $h) * $this->k); $c = $w * $this->k; $d = $h * $this->k; $this->signature_appearance['rect'] = sprintf('%.2F %.2F %.2F %.2F', $a, $b, $a+$c, $b+$d); } /** * Create a new page group. * NOTE: call this function before calling AddPage() * @param int $page starting group page (leave empty for next page). * @access public * @since 3.0.000 (2008-03-27) */ public function startPageGroup($page='') { if (empty($page)) { $page = $this->page + 1; } $this->newpagegroup[$page] = true; } /** * Defines an alias for the total number of pages. * It will be substituted as the document is closed. * @param string $alias The alias. * @access public * @since 1.4 * @see getAliasNbPages(), PageNo(), Footer() */ public function AliasNbPages($alias='{nb}') { $this->AliasNbPages = $alias; } /** * Returns the string alias used for the total number of pages. * If the current font is unicode type, the returned string is surrounded by additional curly braces. * @return string * @access public * @since 4.0.018 (2008-08-08) * @see AliasNbPages(), PageNo(), Footer() */ public function getAliasNbPages() { if ($this->isUnicodeFont()) { return '{'.$this->AliasNbPages.'}'; } return $this->AliasNbPages; } /** * Defines an alias for the page number. * It will be substituted as the document is closed. * @param string $alias The alias. * @access public * @since 4.5.000 (2009-01-02) * @see getAliasNbPages(), PageNo(), Footer() */ public function AliasNumPage($alias='{pnb}') { //Define an alias for total number of pages $this->AliasNumPage = $alias; } /** * Returns the string alias used for the page number. * If the current font is unicode type, the returned string is surrounded by additional curly braces. * @return string * @access public * @since 4.5.000 (2009-01-02) * @see AliasNbPages(), PageNo(), Footer() */ public function getAliasNumPage() { if ($this->isUnicodeFont()) { return '{'.$this->AliasNumPage.'}'; } return $this->AliasNumPage; } /** * Return the current page in the group. * @return current page in the group * @access public * @since 3.0.000 (2008-03-27) */ public function getGroupPageNo() { return $this->pagegroups[$this->currpagegroup]; } /** * Returns the current group page number formatted as a string. * @access public * @since 4.3.003 (2008-11-18) * @see PaneNo(), formatPageNumber() */ public function getGroupPageNoFormatted() { return $this->formatPageNumber($this->getGroupPageNo()); } /** * Return the alias of the current page group * If the current font is unicode type, the returned string is surrounded by additional curly braces. * (will be replaced by the total number of pages in this group). * @return alias of the current page group * @access public * @since 3.0.000 (2008-03-27) */ public function getPageGroupAlias() { if ($this->isUnicodeFont()) { return '{'.$this->currpagegroup.'}'; } return $this->currpagegroup; } /** * Return the alias for the page number on the current page group * If the current font is unicode type, the returned string is surrounded by additional curly braces. * (will be replaced by the total number of pages in this group). * @return alias of the current page group * @access public * @since 4.5.000 (2009-01-02) */ public function getPageNumGroupAlias() { if ($this->isUnicodeFont()) { return '{'.str_replace('{nb', '{pnb', $this->currpagegroup).'}'; } return str_replace('{nb', '{pnb', $this->currpagegroup); } /** * Format the page numbers. * This method can be overriden for custom formats. * @param int $num page number * @access protected * @since 4.2.005 (2008-11-06) */ protected function formatPageNumber($num) { return number_format((float)$num, 0, '', '.'); } /** * Format the page numbers on the Table Of Content. * This method can be overriden for custom formats. * @param int $num page number * @access protected * @since 4.5.001 (2009-01-04) * @see addTOC(), addHTMLTOC() */ protected function formatTOCPageNumber($num) { return number_format((float)$num, 0, '', '.'); } /** * Returns the current page number formatted as a string. * @access public * @since 4.2.005 (2008-11-06) * @see PaneNo(), formatPageNumber() */ public function PageNoFormatted() { return $this->formatPageNumber($this->PageNo()); } /** * Put visibility settings. * @access protected * @since 3.0.000 (2008-03-27) */ protected function _putocg() { $this->n_ocg_print = $this->_newobj(); $this->_out('<< /Type /OCG /Name '.$this->_textstring('print', $this->n_ocg_print).' /Usage << /Print <</PrintState /ON>> /View <</ViewState /OFF>> >> >>'."\n".'endobj'); $this->n_ocg_view = $this->_newobj(); $this->_out('<< /Type /OCG /Name '.$this->_textstring('view', $this->n_ocg_view).' /Usage << /Print <</PrintState /OFF>> /View <</ViewState /ON>> >> >>'."\n".'endobj'); } /** * Set the visibility of the successive elements. * This can be useful, for instance, to put a background * image or color that will show on screen but won't print. * @param string $v visibility mode. Legal values are: all, print, screen. * @access public * @since 3.0.000 (2008-03-27) */ public function setVisibility($v) { if ($this->openMarkedContent) { // close existing open marked-content $this->_out('EMC'); $this->openMarkedContent = false; } switch($v) { case 'print': { $this->_out('/OC /OC1 BDC'); $this->openMarkedContent = true; break; } case 'screen': { $this->_out('/OC /OC2 BDC'); $this->openMarkedContent = true; break; } case 'all': { $this->_out(''); break; } default: { $this->Error('Incorrect visibility: '.$v); break; } } $this->visibility = $v; } /** * Add transparency parameters to the current extgstate * @param array $params parameters * @return the number of extgstates * @access protected * @since 3.0.000 (2008-03-27) */ protected function addExtGState($parms) { $n = count($this->extgstates) + 1; // check if this ExtGState already exist for ($i = 1; $i < $n; ++$i) { if ($this->extgstates[$i]['parms'] == $parms) { // return reference to existing ExtGState return $i; } } $this->extgstates[$n]['parms'] = $parms; return $n; } /** * Add an extgstate * @param array $gs extgstate * @access protected * @since 3.0.000 (2008-03-27) */ protected function setExtGState($gs) { $this->_out(sprintf('/GS%d gs', $gs)); } /** * Put extgstates for object transparency * @param array $gs extgstate * @access protected * @since 3.0.000 (2008-03-27) */ protected function _putextgstates() { $ne = count($this->extgstates); for ($i = 1; $i <= $ne; ++$i) { $this->extgstates[$i]['n'] = $this->_newobj(); $out = '<< /Type /ExtGState'; foreach ($this->extgstates[$i]['parms'] as $k => $v) { if (is_float($v)) { $v = sprintf('%.2F', $v); } $out .= ' /'.$k.' '.$v; } $out .= ' >>'; $out .= "\n".'endobj'; $this->_out($out); } } /** * Set alpha for stroking (CA) and non-stroking (ca) operations. * @param float $alpha real value from 0 (transparent) to 1 (opaque) * @param string $bm blend mode, one of the following: Normal, Multiply, Screen, Overlay, Darken, Lighten, ColorDodge, ColorBurn, HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity * @access public * @since 3.0.000 (2008-03-27) */ public function setAlpha($alpha, $bm='Normal') { $gs = $this->addExtGState(array('ca' => $alpha, 'CA' => $alpha, 'BM' => '/'.$bm, 'AIS' => 'false')); $this->setExtGState($gs); } /** * Set the default JPEG compression quality (1-100) * @param int $quality JPEG quality, integer between 1 and 100 * @access public * @since 3.0.000 (2008-03-27) */ public function setJPEGQuality($quality) { if (($quality < 1) OR ($quality > 100)) { $quality = 75; } $this->jpeg_quality = intval($quality); } /** * Set the default number of columns in a row for HTML tables. * @param int $cols number of columns * @access public * @since 3.0.014 (2008-06-04) */ public function setDefaultTableColumns($cols=4) { $this->default_table_columns = intval($cols); } /** * Set the height of the cell (line height) respect the font height. * @param int $h cell proportion respect font height (typical value = 1.25). * @access public * @since 3.0.014 (2008-06-04) */ public function setCellHeightRatio($h) { $this->cell_height_ratio = $h; } /** * return the height of cell repect font height. * @access public * @since 4.0.012 (2008-07-24) */ public function getCellHeightRatio() { return $this->cell_height_ratio; } /** * Set the PDF version (check PDF reference for valid values). * Default value is 1.t * @access public * @since 3.1.000 (2008-06-09) */ public function setPDFVersion($version='1.7') { $this->PDFVersion = $version; } /** * Set the viewer preferences dictionary controlling the way the document is to be presented on the screen or in print. * (see Section 8.1 of PDF reference, "Viewer Preferences"). * <ul><li>HideToolbar boolean (Optional) A flag specifying whether to hide the viewer application's tool bars when the document is active. Default value: false.</li><li>HideMenubar boolean (Optional) A flag specifying whether to hide the viewer application's menu bar when the document is active. Default value: false.</li><li>HideWindowUI boolean (Optional) A flag specifying whether to hide user interface elements in the document's window (such as scroll bars and navigation controls), leaving only the document's contents displayed. Default value: false.</li><li>FitWindow boolean (Optional) A flag specifying whether to resize the document's window to fit the size of the first displayed page. Default value: false.</li><li>CenterWindow boolean (Optional) A flag specifying whether to position the document's window in the center of the screen. Default value: false.</li><li>DisplayDocTitle boolean (Optional; PDF 1.4) A flag specifying whether the window's title bar should display the document title taken from the Title entry of the document information dictionary (see Section 10.2.1, "Document Information Dictionary"). If false, the title bar should instead display the name of the PDF file containing the document. Default value: false.</li><li>NonFullScreenPageMode name (Optional) The document's page mode, specifying how to display the document on exiting full-screen mode:<ul><li>UseNone Neither document outline nor thumbnail images visible</li><li>UseOutlines Document outline visible</li><li>UseThumbs Thumbnail images visible</li><li>UseOC Optional content group panel visible</li></ul>This entry is meaningful only if the value of the PageMode entry in the catalog dictionary (see Section 3.6.1, "Document Catalog") is FullScreen; it is ignored otherwise. Default value: UseNone.</li><li>ViewArea name (Optional; PDF 1.4) The name of the page boundary representing the area of a page to be displayed when viewing the document on the screen. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li><li>ViewClip name (Optional; PDF 1.4) The name of the page boundary to which the contents of a page are to be clipped when viewing the document on the screen. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li><li>PrintArea name (Optional; PDF 1.4) The name of the page boundary representing the area of a page to be rendered when printing the document. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li><li>PrintClip name (Optional; PDF 1.4) The name of the page boundary to which the contents of a page are to be clipped when printing the document. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li><li>PrintScaling name (Optional; PDF 1.6) The page scaling option to be selected when a print dialog is displayed for this document. Valid values are: <ul><li>None, which indicates that the print dialog should reflect no page scaling</li><li>AppDefault (default), which indicates that applications should use the current print scaling</li></ul></li><li>Duplex name (Optional; PDF 1.7) The paper handling option to use when printing the file from the print dialog. The following values are valid:<ul><li>Simplex - Print single-sided</li><li>DuplexFlipShortEdge - Duplex and flip on the short edge of the sheet</li><li>DuplexFlipLongEdge - Duplex and flip on the long edge of the sheet</li></ul>Default value: none</li><li>PickTrayByPDFSize boolean (Optional; PDF 1.7) A flag specifying whether the PDF page size is used to select the input paper tray. This setting influences only the preset values used to populate the print dialog presented by a PDF viewer application. If PickTrayByPDFSize is true, the check box in the print dialog associated with input paper tray is checked. Note: This setting has no effect on Mac OS systems, which do not provide the ability to pick the input tray by size.</li><li>PrintPageRange array (Optional; PDF 1.7) The page numbers used to initialize the print dialog box when the file is printed. The first page of the PDF file is denoted by 1. Each pair consists of the first and last pages in the sub-range. An odd number of integers causes this entry to be ignored. Negative numbers cause the entire array to be ignored. Default value: as defined by PDF viewer application</li><li>NumCopies integer (Optional; PDF 1.7) The number of copies to be printed when the print dialog is opened for this file. Supported values are the integers 2 through 5. Values outside this range are ignored. Default value: as defined by PDF viewer application, but typically 1</li></ul> * @param array $preferences array of options. * @author Nicola Asuni * @access public * @since 3.1.000 (2008-06-09) */ public function setViewerPreferences($preferences) { $this->viewer_preferences = $preferences; } /** * Paints color transition registration bars * @param float $x abscissa of the top left corner of the rectangle. * @param float $y ordinate of the top left corner of the rectangle. * @param float $w width of the rectangle. * @param float $h height of the rectangle. * @param boolean $transition if true prints tcolor transitions to white. * @param boolean $vertical if true prints bar vertically. * @param string $colors colors to print, one letter per color separated by comma (for example 'A,W,R,G,B,C,M,Y,K'): A=black, W=white, R=red, G=green, B=blue, C=cyan, M=magenta, Y=yellow, K=black. * @author Nicola Asuni * @since 4.9.000 (2010-03-26) * @access public */ public function colorRegistrationBar($x, $y, $w, $h, $transition=true, $vertical=false, $colors='A,R,G,B,C,M,Y,K') { $bars = explode(',', $colors); $numbars = count($bars); // number of bars to print // set bar measures if ($vertical) { $coords = array(0, 0, 0, 1); $wb = $w / $numbars; // bar width $hb = $h; // bar height $xd = $wb; // delta x $yd = 0; // delta y } else { $coords = array(1, 0, 0, 0); $wb = $w; // bar width $hb = $h / $numbars; // bar height $xd = 0; // delta x $yd = $hb; // delta y } $xb = $x; $yb = $y; foreach ($bars as $col) { switch ($col) { // set transition colors case 'A': { // BLACK $col_a = array(255); $col_b = array(0); break; } case 'W': { // WHITE $col_a = array(0); $col_b = array(255); break; } case 'R': { // R $col_a = array(255,255,255); $col_b = array(255,0,0); break; } case 'G': { // G $col_a = array(255,255,255); $col_b = array(0,255,0); break; } case 'B': { // B $col_a = array(255,255,255); $col_b = array(0,0,255); break; } case 'C': { // C $col_a = array(0,0,0,0); $col_b = array(100,0,0,0); break; } case 'M': { // M $col_a = array(0,0,0,0); $col_b = array(0,100,0,0); break; } case 'Y': { // Y $col_a = array(0,0,0,0); $col_b = array(0,0,100,0); break; } case 'K': { // K $col_a = array(0,0,0,0); $col_b = array(0,0,0,100); break; } default: { // GRAY $col_a = array(255); $col_b = array(0); break; } } if ($transition) { // color gradient $this->LinearGradient($xb, $yb, $wb, $hb, $col_a, $col_b, $coords); } else { // color rectangle $this->SetFillColorArray($col_b); $this->Rect($xb, $yb, $wb, $hb, 'F', array()); } $xb += $xd; $yb += $yd; } } /** * Paints crop mark * @param float $x abscissa of the crop mark center. * @param float $y ordinate of the crop mark center. * @param float $w width of the crop mark. * @param float $h height of the crop mark. * @param string $type type of crop mark, one sybol per type separated by comma: A = top left, B = top right, C = bottom left, D = bottom right. * @param array $color crop mark color (default black). * @author Nicola Asuni * @since 4.9.000 (2010-03-26) * @access public */ public function cropMark($x, $y, $w, $h, $type='A,B,C,D', $color=array(0,0,0)) { $this->SetLineStyle(array('width' => (0.5 / $this->k), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $color)); $crops = explode(',', $type); $numcrops = count($crops); // number of crop marks to print $dw = $w / 4; // horizontal space to leave before the intersection point $dh = $h / 4; // vertical space to leave before the intersection point foreach ($crops as $crop) { switch ($crop) { case 'A': { $x1 = $x; $y1 = $y - $h; $x2 = $x; $y2 = $y - $dh; $x3 = $x - $w; $y3 = $y; $x4 = $x - $dw; $y4 = $y; break; } case 'B': { $x1 = $x; $y1 = $y - $h; $x2 = $x; $y2 = $y - $dh; $x3 = $x + $dw; $y3 = $y; $x4 = $x + $w; $y4 = $y; break; } case 'C': { $x1 = $x - $w; $y1 = $y; $x2 = $x - $dw; $y2 = $y; $x3 = $x; $y3 = $y + $dh; $x4 = $x; $y4 = $y + $h; break; } case 'D': { $x1 = $x + $dw; $y1 = $y; $x2 = $x + $w; $y2 = $y; $x3 = $x; $y3 = $y + $dh; $x4 = $x; $y4 = $y + $h; break; } } $this->Line($x1, $y1, $x2, $y2); $this->Line($x3, $y3, $x4, $y4); } } /** * Paints a registration mark * @param float $x abscissa of the registration mark center. * @param float $y ordinate of the registration mark center. * @param float $r radius of the crop mark. * @param boolean $double if true print two concentric crop marks. * @param array $cola crop mark color (default black). * @param array $colb second crop mark color. * @author Nicola Asuni * @since 4.9.000 (2010-03-26) * @access public */ public function registrationMark($x, $y, $r, $double=false, $cola=array(0,0,0), $colb=array(255,255,255)) { $line_style = array('width' => (0.5 / $this->k), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $cola); $this->SetFillColorArray($cola); $this->PieSector($x, $y, $r, 90, 180, 'F'); $this->PieSector($x, $y, $r, 270, 360, 'F'); $this->Circle($x, $y, $r, 0, 360, 'C', $line_style, array(), 8); if ($double) { $r2 = $r * 0.5; $this->SetFillColorArray($colb); $this->PieSector($x, $y, $r2, 90, 180, 'F'); $this->PieSector($x, $y, $r2, 270, 360, 'F'); $this->SetFillColorArray($cola); $this->PieSector($x, $y, $r2, 0, 90, 'F'); $this->PieSector($x, $y, $r2, 180, 270, 'F'); $this->Circle($x, $y, $r2, 0, 360, 'C', $line_style, array(), 8); } } /** * Paints a linear colour gradient. * @param float $x abscissa of the top left corner of the rectangle. * @param float $y ordinate of the top left corner of the rectangle. * @param float $w width of the rectangle. * @param float $h height of the rectangle. * @param array $col1 first color (Grayscale, RGB or CMYK components). * @param array $col2 second color (Grayscale, RGB or CMYK components). * @param array $coords array of the form (x1, y1, x2, y2) which defines the gradient vector (see linear_gradient_coords.jpg). The default value is from left to right (x1=0, y1=0, x2=1, y2=0). * @author Andreas Würmser, Nicola Asuni * @since 3.1.000 (2008-06-09) * @access public */ public function LinearGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0,0,1,0)) { $this->Clip($x, $y, $w, $h); $this->Gradient(2, $coords, array(array('color' => $col1, 'offset' => 0, 'exponent' => 1), array('color' => $col2, 'offset' => 1, 'exponent' => 1)), array(), false); } /** * Paints a radial colour gradient. * @param float $x abscissa of the top left corner of the rectangle. * @param float $y ordinate of the top left corner of the rectangle. * @param float $w width of the rectangle. * @param float $h height of the rectangle. * @param array $col1 first color (Grayscale, RGB or CMYK components). * @param array $col2 second color (Grayscale, RGB or CMYK components). * @param array $coords array of the form (fx, fy, cx, cy, r) where (fx, fy) is the starting point of the gradient with color1, (cx, cy) is the center of the circle with color2, and r is the radius of the circle (see radial_gradient_coords.jpg). (fx, fy) should be inside the circle, otherwise some areas will not be defined. * @author Andreas Würmser, Nicola Asuni * @since 3.1.000 (2008-06-09) * @access public */ public function RadialGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0.5,0.5,0.5,0.5,1)) { $this->Clip($x, $y, $w, $h); $this->Gradient(3, $coords, array(array('color' => $col1, 'offset' => 0, 'exponent' => 1), array('color' => $col2, 'offset' => 1, 'exponent' => 1)), array(), false); } /** * Paints a coons patch mesh. * @param float $x abscissa of the top left corner of the rectangle. * @param float $y ordinate of the top left corner of the rectangle. * @param float $w width of the rectangle. * @param float $h height of the rectangle. * @param array $col1 first color (lower left corner) (RGB components). * @param array $col2 second color (lower right corner) (RGB components). * @param array $col3 third color (upper right corner) (RGB components). * @param array $col4 fourth color (upper left corner) (RGB components). * @param array $coords <ul><li>for one patch mesh: array(float x1, float y1, .... float x12, float y12): 12 pairs of coordinates (normally from 0 to 1) which specify the Bezier control points that define the patch. First pair is the lower left edge point, next is its right control point (control point 2). Then the other points are defined in the order: control point 1, edge point, control point 2 going counter-clockwise around the patch. Last (x12, y12) is the first edge point's left control point (control point 1).</li><li>for two or more patch meshes: array[number of patches]: arrays with the following keys for each patch: f: where to put that patch (0 = first patch, 1, 2, 3 = right, top and left of precedent patch - I didn't figure this out completely - just try and error ;-) points: 12 pairs of coordinates of the Bezier control points as above for the first patch, 8 pairs of coordinates for the following patches, ignoring the coordinates already defined by the precedent patch (I also didn't figure out the order of these - also: try and see what's happening) colors: must be 4 colors for the first patch, 2 colors for the following patches</li></ul> * @param array $coords_min minimum value used by the coordinates. If a coordinate's value is smaller than this it will be cut to coords_min. default: 0 * @param array $coords_max maximum value used by the coordinates. If a coordinate's value is greater than this it will be cut to coords_max. default: 1 * @param boolean $antialias A flag indicating whether to filter the shading function to prevent aliasing artifacts. * @author Andreas Würmser, Nicola Asuni * @since 3.1.000 (2008-06-09) * @access public */ public function CoonsPatchMesh($x, $y, $w, $h, $col1=array(), $col2=array(), $col3=array(), $col4=array(), $coords=array(0.00,0.0,0.33,0.00,0.67,0.00,1.00,0.00,1.00,0.33,1.00,0.67,1.00,1.00,0.67,1.00,0.33,1.00,0.00,1.00,0.00,0.67,0.00,0.33), $coords_min=0, $coords_max=1, $antialias=false) { $this->Clip($x, $y, $w, $h); $n = count($this->gradients) + 1; $this->gradients[$n] = array(); $this->gradients[$n]['type'] = 6; //coons patch mesh $this->gradients[$n]['coords'] = array(); $this->gradients[$n]['antialias'] = $antialias; $this->gradients[$n]['colors'] = array(); $this->gradients[$n]['transparency'] = false; //check the coords array if it is the simple array or the multi patch array if (!isset($coords[0]['f'])) { //simple array -> convert to multi patch array if (!isset($col1[1])) { $col1[1] = $col1[2] = $col1[0]; } if (!isset($col2[1])) { $col2[1] = $col2[2] = $col2[0]; } if (!isset($col3[1])) { $col3[1] = $col3[2] = $col3[0]; } if (!isset($col4[1])) { $col4[1] = $col4[2] = $col4[0]; } $patch_array[0]['f'] = 0; $patch_array[0]['points'] = $coords; $patch_array[0]['colors'][0]['r'] = $col1[0]; $patch_array[0]['colors'][0]['g'] = $col1[1]; $patch_array[0]['colors'][0]['b'] = $col1[2]; $patch_array[0]['colors'][1]['r'] = $col2[0]; $patch_array[0]['colors'][1]['g'] = $col2[1]; $patch_array[0]['colors'][1]['b'] = $col2[2]; $patch_array[0]['colors'][2]['r'] = $col3[0]; $patch_array[0]['colors'][2]['g'] = $col3[1]; $patch_array[0]['colors'][2]['b'] = $col3[2]; $patch_array[0]['colors'][3]['r'] = $col4[0]; $patch_array[0]['colors'][3]['g'] = $col4[1]; $patch_array[0]['colors'][3]['b'] = $col4[2]; } else { //multi patch array $patch_array = $coords; } $bpcd = 65535; //16 bits per coordinate //build the data stream $this->gradients[$n]['stream'] = ''; $count_patch = count($patch_array); for ($i=0; $i < $count_patch; ++$i) { $this->gradients[$n]['stream'] .= chr($patch_array[$i]['f']); //start with the edge flag as 8 bit $count_points = count($patch_array[$i]['points']); for ($j=0; $j < $count_points; ++$j) { //each point as 16 bit $patch_array[$i]['points'][$j] = (($patch_array[$i]['points'][$j] - $coords_min) / ($coords_max - $coords_min)) * $bpcd; if ($patch_array[$i]['points'][$j] < 0) { $patch_array[$i]['points'][$j] = 0; } if ($patch_array[$i]['points'][$j] > $bpcd) { $patch_array[$i]['points'][$j] = $bpcd; } $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] / 256)); $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] % 256)); } $count_cols = count($patch_array[$i]['colors']); for ($j=0; $j < $count_cols; ++$j) { //each color component as 8 bit $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['r']); $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['g']); $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['b']); } } //paint the gradient $this->_out('/Sh'.$n.' sh'); //restore previous Graphic State $this->_out('Q'); } /** * Set a rectangular clipping area. * @param float $x abscissa of the top left corner of the rectangle (or top right corner for RTL mode). * @param float $y ordinate of the top left corner of the rectangle. * @param float $w width of the rectangle. * @param float $h height of the rectangle. * @author Andreas Würmser, Nicola Asuni * @since 3.1.000 (2008-06-09) * @access protected */ protected function Clip($x, $y, $w, $h) { if ($this->rtl) { $x = $this->w - $x - $w; } //save current Graphic State $s = 'q'; //set clipping area $s .= sprintf(' %.2F %.2F %.2F %.2F re W n', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k); //set up transformation matrix for gradient $s .= sprintf(' %.3F 0 0 %.3F %.3F %.3F cm', $w*$this->k, $h*$this->k, $x*$this->k, ($this->h-($y+$h))*$this->k); $this->_out($s); } /** * Output gradient. * @param int $type type of gradient (1 Function-based shading; 2 Axial shading; 3 Radial shading; 4 Free-form Gouraud-shaded triangle mesh; 5 Lattice-form Gouraud-shaded triangle mesh; 6 Coons patch mesh; 7 Tensor-product patch mesh). (Not all types are currently supported) * @param array $coords array of coordinates. * @param array $stops array gradient color components: color = array of GRAY, RGB or CMYK color components; offset = (0 to 1) represents a location along the gradient vector; exponent = exponent of the exponential interpolation function (default = 1). * @param array $background An array of colour components appropriate to the colour space, specifying a single background colour value. * @param boolean $antialias A flag indicating whether to filter the shading function to prevent aliasing artifacts. * @author Nicola Asuni * @since 3.1.000 (2008-06-09) * @access public */ public function Gradient($type, $coords, $stops, $background=array(), $antialias=false) { $n = count($this->gradients) + 1; $this->gradients[$n] = array(); $this->gradients[$n]['type'] = $type; $this->gradients[$n]['coords'] = $coords; $this->gradients[$n]['antialias'] = $antialias; $this->gradients[$n]['colors'] = array(); $this->gradients[$n]['transparency'] = false; // color space $numcolspace = count($stops[0]['color']); $bcolor = array_values($background); switch($numcolspace) { case 4: { // CMYK $this->gradients[$n]['colspace'] = 'DeviceCMYK'; if (!empty($background)) { $this->gradients[$n]['background'] = sprintf('%.3F %.3F %.3F %.3F', $bcolor[0]/100, $bcolor[1]/100, $bcolor[2]/100, $bcolor[3]/100); } break; } case 3: { // RGB $this->gradients[$n]['colspace'] = 'DeviceRGB'; if (!empty($background)) { $this->gradients[$n]['background'] = sprintf('%.3F %.3F %.3F', $bcolor[0]/255, $bcolor[1]/255, $bcolor[2]/255); } break; } case 1: { // Gray scale $this->gradients[$n]['colspace'] = 'DeviceGray'; if (!empty($background)) { $this->gradients[$n]['background'] = sprintf('%.3F', $bcolor[0]/255); } break; } } $num_stops = count($stops); $last_stop_id = $num_stops - 1; foreach ($stops as $key => $stop) { $this->gradients[$n]['colors'][$key] = array(); // offset represents a location along the gradient vector if (isset($stop['offset'])) { $this->gradients[$n]['colors'][$key]['offset'] = $stop['offset']; } else { if ($key == 0) { $this->gradients[$n]['colors'][$key]['offset'] = 0; } elseif ($key == $last_stop_id) { $this->gradients[$n]['colors'][$key]['offset'] = 1; } else { $offsetstep = (1 - $this->gradients[$n]['colors'][($key - 1)]['offset']) / ($num_stops - $key); $this->gradients[$n]['colors'][$key]['offset'] = $this->gradients[$n]['colors'][($key - 1)]['offset'] + $offsetstep; } } if (isset($stop['opacity'])) { $this->gradients[$n]['colors'][$key]['opacity'] = $stop['opacity']; if ($stop['opacity'] < 1) { $this->gradients[$n]['transparency'] = true; } } else { $this->gradients[$n]['colors'][$key]['opacity'] = 1; } // exponent for the exponential interpolation function if (isset($stop['exponent'])) { $this->gradients[$n]['colors'][$key]['exponent'] = $stop['exponent']; } else { $this->gradients[$n]['colors'][$key]['exponent'] = 1; } // set colors $color = array_values($stop['color']); switch($numcolspace) { case 4: { // CMYK $this->gradients[$n]['colors'][$key]['color'] = sprintf('%.3F %.3F %.3F %.3F', $color[0]/100, $color[1]/100, $color[2]/100, $color[3]/100); break; } case 3: { // RGB $this->gradients[$n]['colors'][$key]['color'] = sprintf('%.3F %.3F %.3F', $color[0]/255, $color[1]/255, $color[2]/255); break; } case 1: { // Gray scale $this->gradients[$n]['colors'][$key]['color'] = sprintf('%.3F', $color[0]/255); break; } } } if ($this->gradients[$n]['transparency']) { // paint luminosity gradient $this->_out('/TGS'.$n.' gs'); } //paint the gradient $this->_out('/Sh'.$n.' sh'); //restore previous Graphic State $this->_out('Q'); } /** * Output gradient shaders. * @author Nicola Asuni * @since 3.1.000 (2008-06-09) * @access protected */ function _putshaders() { $idt = count($this->gradients); //index for transparency gradients foreach ($this->gradients as $id => $grad) { if (($grad['type'] == 2) OR ($grad['type'] == 3)) { $fc = $this->_newobj(); $out = '<<'; $out .= ' /FunctionType 3'; $out .= ' /Domain [0 1]'; $functions = ''; $bounds = ''; $encode = ''; $i = 1; $num_cols = count($grad['colors']); $lastcols = $num_cols - 1; for ($i = 1; $i < $num_cols; ++$i) { $functions .= ($fc + $i).' 0 R '; if ($i < $lastcols) { $bounds .= sprintf('%.3F ', $grad['colors'][$i]['offset']); } $encode .= '0 1 '; } $out .= ' /Functions ['.trim($functions).']'; $out .= ' /Bounds ['.trim($bounds).']'; $out .= ' /Encode ['.trim($encode).']'; $out .= ' >>'; $out .= "\n".'endobj'; $this->_out($out); for ($i = 1; $i < $num_cols; ++$i) { $this->_newobj(); $out = '<<'; $out .= ' /FunctionType 2'; $out .= ' /Domain [0 1]'; $out .= ' /C0 ['.$grad['colors'][($i - 1)]['color'].']'; $out .= ' /C1 ['.$grad['colors'][$i]['color'].']'; $out .= ' /N '.$grad['colors'][$i]['exponent']; $out .= ' >>'; $out .= "\n".'endobj'; $this->_out($out); } // set transparency fuctions if ($grad['transparency']) { $ft = $this->_newobj(); $out = '<<'; $out .= ' /FunctionType 3'; $out .= ' /Domain [0 1]'; $functions = ''; $i = 1; $num_cols = count($grad['colors']); for ($i = 1; $i < $num_cols; ++$i) { $functions .= ($ft + $i).' 0 R '; } $out .= ' /Functions ['.trim($functions).']'; $out .= ' /Bounds ['.trim($bounds).']'; $out .= ' /Encode ['.trim($encode).']'; $out .= ' >>'; $out .= "\n".'endobj'; $this->_out($out); for ($i = 1; $i < $num_cols; ++$i) { $this->_newobj(); $out = '<<'; $out .= ' /FunctionType 2'; $out .= ' /Domain [0 1]'; $out .= ' /C0 ['.$grad['colors'][($i - 1)]['opacity'].']'; $out .= ' /C1 ['.$grad['colors'][$i]['opacity'].']'; $out .= ' /N '.$grad['colors'][$i]['exponent']; $out .= ' >>'; $out .= "\n".'endobj'; $this->_out($out); } } } // set shading object $this->_newobj(); $out = '<< /ShadingType '.$grad['type']; if (isset($grad['colspace'])) { $out .= ' /ColorSpace /'.$grad['colspace']; } else { $out .= ' /ColorSpace /DeviceRGB'; } if (isset($grad['background']) AND !empty($grad['background'])) { $out .= ' /Background ['.$grad['background'].']'; } if (isset($grad['antialias']) AND ($grad['antialias'] === true)) { $out .= ' /AntiAlias true'; } if ($grad['type'] == 2) { $out .= ' '.sprintf('/Coords [%.3F %.3F %.3F %.3F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3]); $out .= ' /Domain [0 1]'; $out .= ' /Function '.$fc.' 0 R'; $out .= ' /Extend [true true]'; $out .= ' >>'; } elseif ($grad['type'] == 3) { //x0, y0, r0, x1, y1, r1 //at this this time radius of inner circle is 0 $out .= ' '.sprintf('/Coords [%.3F %.3F 0 %.3F %.3F %.3F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3], $grad['coords'][4]); $out .= ' /Domain [0 1]'; $out .= ' /Function '.$fc.' 0 R'; $out .= ' /Extend [true true]'; $out .= ' >>'; } elseif ($grad['type'] == 6) { $out .= ' /BitsPerCoordinate 16'; $out .= ' /BitsPerComponent 8'; $out .= ' /Decode[0 1 0 1 0 1 0 1 0 1]'; $out .= ' /BitsPerFlag 8'; $stream = $this->_getrawstream($grad['stream']); $out .= ' /Length '.strlen($stream); $out .= ' >>'; $out .= ' stream'."\n".$stream."\n".'endstream'; } $out .= "\n".'endobj'; $this->_out($out); if ($grad['transparency']) { $shading_transparency = preg_replace('/\/ColorSpace \/[^\s]+/si', '/ColorSpace /DeviceGray', $out); $shading_transparency = preg_replace('/\/Function [0-9]+ /si', '/Function '.$ft.' ', $shading_transparency); } $this->gradients[$id]['id'] = $this->n; // set pattern object $this->_newobj(); $out = '<< /Type /Pattern /PatternType 2'; $out .= ' /Shading '.$this->gradients[$id]['id'].' 0 R'; $out .= ' >>'; $out .= "\n".'endobj'; $this->_out($out); $this->gradients[$id]['pattern'] = $this->n; // set shading and pattern for transparency mask if ($grad['transparency']) { // luminosity pattern $idgs = $id + $idt; $this->_newobj(); $this->_out($shading_transparency); $this->gradients[$idgs]['id'] = $this->n; $this->_newobj(); $out = '<< /Type /Pattern /PatternType 2'; $out .= ' /Shading '.$this->gradients[$idgs]['id'].' 0 R'; $out .= ' >>'; $out .= "\n".'endobj'; $this->_out($out); $this->gradients[$idgs]['pattern'] = $this->n; // luminosity XObject $oid = $this->_newobj(); $this->xobjects['LX'.$oid] = array('n' => $oid); $filter = ''; $stream = 'q /a0 gs /Pattern cs /p'.$idgs.' scn 0 0 '.$this->wPt.' '.$this->hPt.' re f Q'; if ($this->compress) { $filter = ' /Filter /FlateDecode'; $stream = gzcompress($stream); } $stream = $this->_getrawstream($stream); $out = '<< /Type /XObject /Subtype /Form /FormType 1'.$filter; $out .= ' /Length '.strlen($stream); $rect = sprintf('%.2F %.2F', $this->wPt, $this->hPt); $out .= ' /BBox [0 0 '.$rect.']'; $out .= ' /Group << /Type /Group /S /Transparency /CS /DeviceGray >>'; $out .= ' /Resources <<'; $out .= ' /ExtGState << /a0 << /ca 1 /CA 1 >> >>'; $out .= ' /Pattern << /p'.$idgs.' '.$this->gradients[$idgs]['pattern'].' 0 R >>'; $out .= ' >>'; $out .= ' >> '; $out .= ' stream'."\n".$stream."\n".'endstream'; $out .= "\n".'endobj'; $this->_out($out); // SMask $this->_newobj(); $out = '<< /Type /Mask /S /Luminosity /G '.($this->n - 1).' 0 R >>'."\n".'endobj'; $this->_out($out); // ExtGState $this->_newobj(); $out = '<< /Type /ExtGState /SMask '.($this->n - 1).' 0 R /AIS false >>'."\n".'endobj'; $this->_out($out); $this->extgstates[] = array('n' => $this->n, 'name' => 'TGS'.$id); } } } /** * Draw the sector of a circle. * It can be used for instance to render pie charts. * @param float $xc abscissa of the center. * @param float $yc ordinate of the center. * @param float $r radius. * @param float $a start angle (in degrees). * @param float $b end angle (in degrees). * @param string $style Style of rendering. See the getPathPaintOperator() function for more information. * @param float $cw: indicates whether to go clockwise (default: true). * @param float $o: origin of angles (0 for 3 o'clock, 90 for noon, 180 for 9 o'clock, 270 for 6 o'clock). Default: 90. * @author Maxime Delorme, Nicola Asuni * @since 3.1.000 (2008-06-09) * @access public */ public function PieSector($xc, $yc, $r, $a, $b, $style='FD', $cw=true, $o=90) { $this->PieSectorXY($xc, $yc, $r, $r, $a, $b, $style, $cw, $o); } /** * Draw the sector of an ellipse. * It can be used for instance to render pie charts. * @param float $xc abscissa of the center. * @param float $yc ordinate of the center. * @param float $rx the x-axis radius. * @param float $ry the y-axis radius. * @param float $a start angle (in degrees). * @param float $b end angle (in degrees). * @param string $style Style of rendering. See the getPathPaintOperator() function for more information. * @param float $cw: indicates whether to go clockwise. * @param float $o: origin of angles (0 for 3 o'clock, 90 for noon, 180 for 9 o'clock, 270 for 6 o'clock). * @param integer $nc Number of curves used to draw a 90 degrees portion of arc. * @author Maxime Delorme, Nicola Asuni * @since 3.1.000 (2008-06-09) * @access public */ public function PieSectorXY($xc, $yc, $rx, $ry, $a, $b, $style='FD', $cw=false, $o=0, $nc=2) { if ($this->rtl) { $xc = $this->w - $xc; } $op = $this->getPathPaintOperator($style); if ($op == 'f') { $line_style = array(); } if ($cw) { $d = $b; $b = 360 - $a + $o; $a = 360 - $d + $o; } else { $b += $o; $a += $o; } $this->_outellipticalarc($xc, $yc, $rx, $ry, 0, $a, $b, true, $nc); $this->_out($op); } /** * Embed vector-based Adobe Illustrator (AI) or AI-compatible EPS files. * NOTE: EPS is not yet fully implemented, use the setRasterizeVectorImages() method to enable/disable rasterization of vector images using ImageMagick library. * Only vector drawing is supported, not text or bitmap. * Although the script was successfully tested with various AI format versions, best results are probably achieved with files that were exported in the AI3 format (tested with Illustrator CS2, Freehand MX and Photoshop CS2). * @param string $file Name of the file containing the image. * @param float $x Abscissa of the upper-left corner. * @param float $y Ordinate of the upper-left corner. * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated. * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated. * @param mixed $link URL or identifier returned by AddLink(). * @param boolean useBoundingBox specifies whether to position the bounding box (true) or the complete canvas (false) at location (x,y). Default value is true. * @param string $align Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul> * @param string $palign Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul> * @param mixed $border Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0))) * @param boolean $fitonpage if true the image is resized to not exceed page dimensions. * @author Valentin Schmidt, Nicola Asuni * @since 3.1.000 (2008-06-09) * @access public */ public function ImageEps($file, $x='', $y='', $w=0, $h=0, $link='', $useBoundingBox=true, $align='', $palign='', $border=0, $fitonpage=false) { if ($this->rasterize_vector_images AND ($w > 0) AND ($h > 0)) { // convert EPS to raster image using GD or ImageMagick libraries return $this->Image($file, $x, $y, $w, $h, 'EPS', $link, $align, true, 300, $palign, false, false, $border, false, false, $fitonpage); } if ($x === '') { $x = $this->x; } if ($y === '') { $y = $this->y; } $k = $this->k; $data = file_get_contents($file); if ($data === false) { $this->Error('EPS file not found: '.$file); } $regs = array(); // EPS/AI compatibility check (only checks files created by Adobe Illustrator!) preg_match("/%%Creator:([^\r\n]+)/", $data, $regs); # find Creator if (count($regs) > 1) { $version_str = trim($regs[1]); # e.g. "Adobe Illustrator(R) 8.0" if (strpos($version_str, 'Adobe Illustrator') !== false) { $versexp = explode(' ', $version_str); $version = (float)array_pop($versexp); if ($version >= 9) { $this->Error('This version of Adobe Illustrator file is not supported: '.$file); } } } // strip binary bytes in front of PS-header $start = strpos($data, '%!PS-Adobe'); if ($start > 0) { $data = substr($data, $start); } // find BoundingBox params preg_match("/%%BoundingBox:([^\r\n]+)/", $data, $regs); if (count($regs) > 1) { list($x1, $y1, $x2, $y2) = explode(' ', trim($regs[1])); } else { $this->Error('No BoundingBox found in EPS file: '.$file); } $start = strpos($data, '%%EndSetup'); if ($start === false) { $start = strpos($data, '%%EndProlog'); } if ($start === false) { $start = strpos($data, '%%BoundingBox'); } $data = substr($data, $start); $end = strpos($data, '%%PageTrailer'); if ($end===false) { $end = strpos($data, 'showpage'); } if ($end) { $data = substr($data, 0, $end); } // calculate image width and height on document if (($w <= 0) AND ($h <= 0)) { $w = ($x2 - $x1) / $k; $h = ($y2 - $y1) / $k; } elseif ($w <= 0) { $w = ($x2-$x1) / $k * ($h / (($y2 - $y1) / $k)); } elseif ($h <= 0) { $h = ($y2 - $y1) / $k * ($w / (($x2 - $x1) / $k)); } // fit the image on available space $this->fitBlock($w, $h, $x, $y, $fitonpage); if ($this->rasterize_vector_images) { // convert EPS to raster image using GD or ImageMagick libraries return $this->Image($file, $x, $y, $w, $h, 'EPS', $link, $align, true, 300, $palign, false, false, $border, false, false, $fitonpage); } // set scaling factors $scale_x = $w / (($x2 - $x1) / $k); $scale_y = $h / (($y2 - $y1) / $k); // set alignment $this->img_rb_y = $y + $h; // set alignment if ($this->rtl) { if ($palign == 'L') { $ximg = $this->lMargin; } elseif ($palign == 'C') { $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2; } elseif ($palign == 'R') { $ximg = $this->w - $this->rMargin - $w; } else { $ximg = $x - $w; } $this->img_rb_x = $ximg; } else { if ($palign == 'L') { $ximg = $this->lMargin; } elseif ($palign == 'C') { $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2; } elseif ($palign == 'R') { $ximg = $this->w - $this->rMargin - $w; } else { $ximg = $x; } $this->img_rb_x = $ximg + $w; } if ($useBoundingBox) { $dx = $ximg * $k - $x1; $dy = $y * $k - $y1; } else { $dx = $ximg * $k; $dy = $y * $k; } // save the current graphic state $this->_out('q'.$this->epsmarker); // translate $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', 1, 0, 0, 1, $dx, $dy + ($this->hPt - (2 * $y * $k) - ($y2 - $y1)))); // scale if (isset($scale_x)) { $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', $scale_x, 0, 0, $scale_y, $x1 * (1 - $scale_x), $y2 * (1 - $scale_y))); } // handle pc/unix/mac line endings preg_match('/[\r\n]+/s', $data, $regs); $lines = explode($regs[0], $data); $u=0; $cnt = count($lines); for ($i=0; $i < $cnt; ++$i) { $line = $lines[$i]; if (($line == '') OR ($line{0} == '%')) { continue; } $len = strlen($line); $chunks = explode(' ', $line); $cmd = array_pop($chunks); // RGB if (($cmd == 'Xa') OR ($cmd == 'XA')) { $b = array_pop($chunks); $g = array_pop($chunks); $r = array_pop($chunks); $this->_out(''.$r.' '.$g.' '.$b.' '.($cmd=='Xa'?'rg':'RG')); //substr($line, 0, -2).'rg' -> in EPS (AI8): c m y k r g b rg! continue; } switch ($cmd) { case 'm': case 'l': case 'v': case 'y': case 'c': case 'k': case 'K': case 'g': case 'G': case 's': case 'S': case 'J': case 'j': case 'w': case 'M': case 'd': case 'n': { $this->_out($line); break; } case 'x': {// custom fill color list($c,$m,$y,$k) = $chunks; $this->_out(''.$c.' '.$m.' '.$y.' '.$k.' k'); break; } case 'X': { // custom stroke color list($c,$m,$y,$k) = $chunks; $this->_out(''.$c.' '.$m.' '.$y.' '.$k.' K'); break; } case 'Y': case 'N': case 'V': case 'L': case 'C': { $line{$len-1} = strtolower($cmd); $this->_out($line); break; } case 'b': case 'B': { $this->_out($cmd . '*'); break; } case 'f': case 'F': { if ($u > 0) { $isU = false; $max = min($i+5, $cnt); for ($j=$i+1; $j < $max; ++$j) { $isU = ($isU OR (($lines[$j] == 'U') OR ($lines[$j] == '*U'))); } if ($isU) { $this->_out('f*'); } } else { $this->_out('f*'); } break; } case '*u': { ++$u; break; } case '*U': { --$u; break; } } } // restore previous graphic state $this->_out($this->epsmarker.'Q'); if (!empty($border)) { $bx = $this->x; $by = $this->y; $this->x = $ximg; if ($this->rtl) { $this->x += $w; } $this->y = $y; $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true); $this->x = $bx; $this->y = $by; } if ($link) { $this->Link($ximg, $y, $w, $h, $link, 0); } // set pointer to align the next text/objects switch($align) { case 'T':{ $this->y = $y; $this->x = $this->img_rb_x; break; } case 'M':{ $this->y = $y + round($h/2); $this->x = $this->img_rb_x; break; } case 'B':{ $this->y = $this->img_rb_y; $this->x = $this->img_rb_x; break; } case 'N':{ $this->SetY($this->img_rb_y); break; } default:{ break; } } $this->endlinex = $this->img_rb_x; } /** * Set document barcode. * @param string $bc barcode * @access public */ public function setBarcode($bc='') { $this->barcode = $bc; } /** * Get current barcode. * @return string * @access public * @since 4.0.012 (2008-07-24) */ public function getBarcode() { return $this->barcode; } /** * Print a Linear Barcode. * @param string $code code to print * @param string $type type of barcode (see barcodes.php for supported formats). * @param int $x x position in user units (empty string = current x position) * @param int $y y position in user units (empty string = current y position) * @param int $w width in user units (empty string = remaining page width) * @param int $h height in user units (empty string = remaining page height) * @param float $xres width of the smallest bar in user units (empty string = default value = 0.4mm) * @param array $style array of options:<ul> <li>boolean $style['border'] if true prints a border</li> <li>int $style['padding'] padding to leave around the barcode (minimum distance between the barcode and the containing cell border) in user units (set to 'auto' for automatic padding)</li><li>array $style['fgcolor'] color array for bars and text</li><li>mixed $style['bgcolor'] color array for background (set to false for transparent)</li><li>boolean $style["text"] boolean if true prints text below the barcode</li><li>string $style['font'] font name for text</li><li>int $style['fontsize'] font size for text</li><li>int $style['stretchtext']: 0 = disabled; 1 = horizontal scaling only if necessary; 2 = forced horizontal scaling; 3 = character spacing only if necessary; 4 = forced character spacing.</li><li>string $style['position'] horizontal position of the containing barcode cell on the page: L = left margin; C = center; R = right margin.</li><li>string $style['align'] horizontal position of the barcode on the containing rectangle: L = left; C = center; R = right.</li><li>string $style['stretch'] if true stretch the barcode to best fit the available width, otherwise uses $xres resolution for a single bar.</li><li>string $style['fitwidth'] if true reduce the width to fit the barcode width + padding. When this option is enabled the 'stretch' option is automatically disabled.</li><li>string $style['cellfitalign'] this option works only when 'fitwidth' is true and 'position' is unset or empty. Set the horizontal position of the containing barcode cell inside the specified rectangle: L = left; C = center; R = right.</li></ul> * @param string $align Indicates the alignment of the pointer next to barcode insertion relative to barcode height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul> * @author Nicola Asuni * @since 3.1.000 (2008-06-09) * @access public */ public function write1DBarcode($code, $type, $x='', $y='', $w='', $h='', $xres='', $style='', $align='') { if ($this->empty_string(trim($code))) { return; } require_once(dirname(__FILE__).'/barcodes.php'); // save current graphic settings $gvars = $this->getGraphicVars(); // create new barcode object $barcodeobj = new TCPDFBarcode($code, $type); $arrcode = $barcodeobj->getBarcodeArray(); if ($arrcode === false) { $this->Error('Error in 1D barcode string'); } // set default values if (!isset($style['position'])) { $style['position'] = ''; } elseif ($style['position'] == 'S') { // keep this for backward compatibility $style['position'] = ''; $style['stretch'] = true; } if (!isset($style['fitwidth'])) { if (!isset($style['stretch'])) { $style['fitwidth'] = true; } else { $style['fitwidth'] = false; } } if ($style['fitwidth']) { // disable stretch $style['stretch'] = false; } if (!isset($style['stretch'])) { if (($w === '') OR ($w <= 0)) { $style['stretch'] = false; } else { $style['stretch'] = true; } } if (!isset($style['fgcolor'])) { $style['fgcolor'] = array(0,0,0); // default black } if (!isset($style['bgcolor'])) { $style['bgcolor'] = false; // default transparent } if (!isset($style['border'])) { $style['border'] = false; } $fontsize = 0; if (!isset($style['text'])) { $style['text'] = false; } if ($style['text'] AND isset($style['font'])) { if (isset($style['fontsize'])) { $fontsize = $style['fontsize']; } $this->SetFont($style['font'], '', $fontsize); } if (!isset($style['stretchtext'])) { $style['stretchtext'] = 4; } if ($x === '') { $x = $this->x; } if ($y === '') { $y = $this->y; } if (($w === '') OR ($w <= 0)) { if ($this->rtl) { $w = $x - $this->lMargin; } else { $w = $this->w - $this->rMargin - $x; } } // horizontal padding if (!isset($style['padding'])) { $hpadding = 0; } elseif ($style['padding'] === 'auto') { $hpadding = 5 * ($w / ($arrcode['maxw'] + 10)); } else { $hpadding = $style['padding']; } // calculate xres (single bar width) $max_xres = ($w - (2 * $hpadding)) / $arrcode['maxw']; if ($style['stretch']) { $xres = $max_xres; } else { if ($this->empty_string($xres)) { $xres = (0.141 * $this->k); // default bar width = 0.4 mm } if ($xres > $max_xres) { // correct xres to fit on $w $max_xres = $max_xres; } if (isset($style['padding']) AND ($style['padding'] === 'auto')) { $hpadding = 5 * $xres; } } if ($style['fitwidth']) { $wold = $w; $w = (($arrcode['maxw'] * $xres) + (2 * $hpadding)); if (isset($style['cellfitalign'])) { switch ($style['cellfitalign']) { case 'L': { if ($this->rtl) { $x -= ($wold - $w); } break; } case 'R': { if (!$this->rtl) { $x += ($wold - $w); } break; } case 'C': { if ($this->rtl) { $x -= (($wold - $w) / 2); } else { $x += (($wold - $w) / 2); } break; } default : { break; } } } } // vertical padding $vpadding = $hpadding; $text_height = ($this->cell_height_ratio * $fontsize / $this->k); // height if (($h === '') OR ($h <= 0)) { // set default height $h = (($arrcode['maxw'] * $xres) / 3) + (2 * $vpadding) + $text_height; } $barh = $h - $text_height - (2 * $vpadding); if ($barh <=0) { // try to reduce font or padding to fit barcode on available height if ($text_height > $h) { $fontsize = (($h * $this->k) / (4 * $this->cell_height_ratio)); $text_height = ($this->cell_height_ratio * $fontsize / $this->k); $this->SetFont($style['font'], '', $fontsize); } if ($vpadding > 0) { $vpadding = (($h - $text_height) / 4); } $barh = $h - $text_height - (2 * $vpadding); } // fit the barcode on available space $this->fitBlock($w, $h, $x, $y, false); // set alignment $this->img_rb_y = $y + $h; // set alignment if ($this->rtl) { if ($style['position'] == 'L') { $xpos = $this->lMargin; } elseif ($style['position'] == 'C') { $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2; } elseif ($style['position'] == 'R') { $xpos = $this->w - $this->rMargin - $w; } else { $xpos = $x - $w; } $this->img_rb_x = $xpos; } else { if ($style['position'] == 'L') { $xpos = $this->lMargin; } elseif ($style['position'] == 'C') { $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2; } elseif ($style['position'] == 'R') { $xpos = $this->w - $this->rMargin - $w; } else { $xpos = $x; } $this->img_rb_x = $xpos + $w; } $xpos_rect = $xpos; if (!isset($style['align'])) { $style['align'] = 'C'; } switch ($style['align']) { case 'L': { $xpos = $xpos_rect + $hpadding; break; } case 'R': { $xpos = $xpos_rect + ($w - ($arrcode['maxw'] * $xres)) - $hpadding; break; } case 'C': default : { $xpos = $xpos_rect + (($w - ($arrcode['maxw'] * $xres)) / 2); break; } } $xpos_text = $xpos; // barcode is always printed in LTR direction $tempRTL = $this->rtl; $this->rtl = false; // print background color if ($style['bgcolor']) { $this->Rect($xpos_rect, $y, $w, $h, $style['border'] ? 'DF' : 'F', '', $style['bgcolor']); } elseif ($style['border']) { $this->Rect($xpos_rect, $y, $w, $h, 'D'); } // set foreground color $this->SetDrawColorArray($style['fgcolor']); $this->SetTextColorArray($style['fgcolor']); // print bars foreach ($arrcode['bcode'] as $k => $v) { $bw = ($v['w'] * $xres); if ($v['t']) { // draw a vertical bar $ypos = $y + $vpadding + ($v['p'] * $barh / $arrcode['maxh']); $this->Rect($xpos, $ypos, $bw, ($v['h'] * $barh / $arrcode['maxh']), 'F', array(), $style['fgcolor']); } $xpos += $bw; } // print text if ($style['text']) { $txtwidth = ($arrcode['maxw'] * $xres); if ($this->GetStringWidth($code) > $txtwidth) { $style['stretchtext'] = 2; } // print text $this->x = $xpos_text; $this->y = $y + $vpadding + $barh; $cmargin = $this->cMargin; $this->cMargin = 0; $this->Cell($txtwidth, '', $code, 0, 0, 'C', 0, '', $style['stretchtext'], false, 'T', 'T'); $this->cMargin = $cmargin; } // restore original direction $this->rtl = $tempRTL; // restore previous settings $this->setGraphicVars($gvars); // set pointer to align the next text/objects switch($align) { case 'T':{ $this->y = $y; $this->x = $this->img_rb_x; break; } case 'M':{ $this->y = $y + round($h / 2); $this->x = $this->img_rb_x; break; } case 'B':{ $this->y = $this->img_rb_y; $this->x = $this->img_rb_x; break; } case 'N':{ $this->SetY($this->img_rb_y); break; } default:{ break; } } $this->endlinex = $this->img_rb_x; } /** * This function is DEPRECATED, please use the new write1DBarcode() function. * @param int $x x position in user units * @param int $y y position in user units * @param int $w width in user units * @param int $h height position in user units * @param string $type type of barcode * @param string $style barcode style * @param string $font font for text * @param int $xres x resolution * @param string $code code to print * @deprecated deprecated since version 3.1.000 (2008-06-10) * @access public * @see write1DBarcode() */ public function writeBarcode($x, $y, $w, $h, $type, $style, $font, $xres, $code) { // convert old settings for the new write1DBarcode() function. $xres = 1 / $xres; $newstyle = array( 'position' => '', 'align' => '', 'stretch' => false, 'fitwidth' => false, 'cellfitalign' => '', 'border' => false, 'padding' => 0, 'fgcolor' => array(0,0,0), 'bgcolor' => false, 'text' => true, 'font' => $font, 'fontsize' => 8, 'stretchtext' => 4 ); if ($style & 1) { $newstyle['border'] = true; } if ($style & 2) { $newstyle['bgcolor'] = false; } if ($style & 4) { $newstyle['position'] = 'C'; } elseif ($style & 8) { $newstyle['position'] = 'L'; } elseif ($style & 16) { $newstyle['position'] = 'R'; } if ($style & 128) { $newstyle['text'] = true; } if ($style & 256) { $newstyle['stretchtext'] = 4; } $this->write1DBarcode($code, $type, $x, $y, $w, $h, $xres, $newstyle, ''); } /** * Print 2D Barcode. * @param string $code code to print * @param string $type type of barcode (see 2dbarcodes.php for supported formats). * @param int $x x position in user units * @param int $y y position in user units * @param int $w width in user units * @param int $h height in user units * @param array $style array of options:<ul><li>boolean $style['border'] if true prints a border around the barcode</li><li>int $style['padding'] padding to leave around the barcode in barcode units (set to 'auto' for automatic padding)</li><li>int $style['hpadding'] horizontal padding in barcode units (set to 'auto' for automatic padding)</li><li>int $style['vpadding'] vertical padding in barcode units (set to 'auto' for automatic padding)</li><li>int $style['module_width'] width of a single module in points</li><li>int $style['module_height'] height of a single module in points</li><li>array $style['fgcolor'] color array for bars and text</li><li>mixed $style['bgcolor'] color array for background or false for transparent</li><li>string $style['position'] barcode position on the page: L = left margin; C = center; R = right margin; S = stretch</li><li>$style['module_width'] width of a single module in points</li><li>$style['module_height'] height of a single module in points</li></ul> * @param string $align Indicates the alignment of the pointer next to barcode insertion relative to barcode height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul> * @param boolean $distort if true distort the barcode to fit width and height, otherwise preserve aspect ratio * @author Nicola Asuni * @since 4.5.037 (2009-04-07) * @access public */ public function write2DBarcode($code, $type, $x='', $y='', $w='', $h='', $style='', $align='', $distort=false) { if ($this->empty_string(trim($code))) { return; } require_once(dirname(__FILE__).'/2dbarcodes.php'); // save current graphic settings $gvars = $this->getGraphicVars(); // create new barcode object $barcodeobj = new TCPDF2DBarcode($code, $type); $arrcode = $barcodeobj->getBarcodeArray(); if (($arrcode === false) OR empty($arrcode)) { $this->Error('Error in 2D barcode string'); } // set default values if (!isset($style['position'])) { $style['position'] = ''; } if (!isset($style['fgcolor'])) { $style['fgcolor'] = array(0,0,0); // default black } if (!isset($style['bgcolor'])) { $style['bgcolor'] = false; // default transparent } if (!isset($style['border'])) { $style['border'] = false; } // padding if (!isset($style['padding'])) { $style['padding'] = 0; } elseif ($style['padding'] === 'auto') { $style['padding'] = 4; } if (!isset($style['hpadding'])) { $style['hpadding'] = $style['padding']; } elseif ($style['hpadding'] === 'auto') { $style['hpadding'] = 4; } if (!isset($style['vpadding'])) { $style['vpadding'] = $style['padding']; } elseif ($style['vpadding'] === 'auto') { $style['vpadding'] = 4; } // cell (module) dimension if (!isset($style['module_width'])) { $style['module_width'] = 1; // width of a single module in points } if (!isset($style['module_height'])) { $style['module_height'] = 1; // height of a single module in points } if ($x === '') { $x = $this->x; } if ($y === '') { $y = $this->y; } // number of barcode columns and rows $rows = $arrcode['num_rows']; $cols = $arrcode['num_cols']; // module width and height $mw = $style['module_width']; $mh = $style['module_height']; // get max dimensions if ($this->rtl) { $maxw = $x - $this->lMargin; } else { $maxw = $this->w - $this->rMargin - $x; } $maxh = ($this->h - $this->tMargin - $this->bMargin); $ratioHW = ($rows * $mh) / ($cols * $mw); $ratioWH = ($cols * $mw) / ($rows * $mh); if (!$distort) { if (($maxw * $ratioHW) > $maxh) { $maxw = $maxh * $ratioWH; } if (($maxh * $ratioWH) > $maxw) { $maxh = $maxw * $ratioHW; } } // set maximum dimesions if ($w > $maxw) { $w = $maxw; } if ($h > $maxh) { $h = $maxh; } $hpad = (2 * $style['hpadding']); $vpad = (2 * $style['vpadding']); // set dimensions if ((($w === '') OR ($w <= 0)) AND (($h === '') OR ($h <= 0))) { $w = ($cols + $hpad) * ($mw / $this->k); $h = ($rows + $vpad) * ($mh / $this->k); } elseif (($w === '') OR ($w <= 0)) { $w = $h * $ratioWH; } elseif (($h === '') OR ($h <= 0)) { $h = $w * $ratioHW; } // barcode size (excluding padding) $bw = ($w * $cols) / ($cols + $hpad); $bh = ($h * $rows) / ($rows + $vpad); // dimension of single barcode cell unit $cw = $bw / $cols; $ch = $bh / $rows; if (!$distort) { if (($cw / $ch) > ($mw / $mh)) { // correct horizontal distortion $cw = $ch * $mw / $mh; $bw = $cw * $cols; $style['hpadding'] = ($w - $bw) / (2 * $cw); } else { // correct vertical distortion $ch = $cw * $mh / $mw; $bh = $ch * $rows; $style['vpadding'] = ($h - $bh) / (2 * $ch); } } // fit the barcode on available space $this->fitBlock($w, $h, $x, $y, false); // set alignment $this->img_rb_y = $y + $h; // set alignment if ($this->rtl) { if ($style['position'] == 'L') { $xpos = $this->lMargin; } elseif ($style['position'] == 'C') { $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2; } elseif ($style['position'] == 'R') { $xpos = $this->w - $this->rMargin - $w; } else { $xpos = $x - $w; } $this->img_rb_x = $xpos; } else { if ($style['position'] == 'L') { $xpos = $this->lMargin; } elseif ($style['position'] == 'C') { $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2; } elseif ($style['position'] == 'R') { $xpos = $this->w - $this->rMargin - $w; } else { $xpos = $x; } $this->img_rb_x = $xpos + $w; } $xstart = $xpos + ($style['hpadding'] * $cw); $ystart = $y + ($style['vpadding'] * $ch); // barcode is always printed in LTR direction $tempRTL = $this->rtl; $this->rtl = false; // print background color if ($style['bgcolor']) { $this->Rect($xpos, $y, $w, $h, $style['border'] ? 'DF' : 'F', '', $style['bgcolor']); } elseif ($style['border']) { $this->Rect($xpos, $y, $w, $h, 'D'); } // set foreground color $this->SetDrawColorArray($style['fgcolor']); // print barcode cells // for each row for ($r = 0; $r < $rows; ++$r) { $xr = $xstart; // for each column for ($c = 0; $c < $cols; ++$c) { if ($arrcode['bcode'][$r][$c] == 1) { // draw a single barcode cell $this->Rect($xr, $ystart, $cw, $ch, 'F', array(), $style['fgcolor']); } $xr += $cw; } $ystart += $ch; } // restore original direction $this->rtl = $tempRTL; // restore previous settings $this->setGraphicVars($gvars); // set pointer to align the next text/objects switch($align) { case 'T':{ $this->y = $y; $this->x = $this->img_rb_x; break; } case 'M':{ $this->y = $y + round($h/2); $this->x = $this->img_rb_x; break; } case 'B':{ $this->y = $this->img_rb_y; $this->x = $this->img_rb_x; break; } case 'N':{ $this->SetY($this->img_rb_y); break; } default:{ break; } } $this->endlinex = $this->img_rb_x; } /** * Returns an array containing current margins: * <ul> <li>$ret['left'] = left margin</li> <li>$ret['right'] = right margin</li> <li>$ret['top'] = top margin</li> <li>$ret['bottom'] = bottom margin</li> <li>$ret['header'] = header margin</li> <li>$ret['footer'] = footer margin</li> <li>$ret['cell'] = cell margin</li> * </ul> * @return array containing all margins measures * @access public * @since 3.2.000 (2008-06-23) */ public function getMargins() { $ret = array( 'left' => $this->lMargin, 'right' => $this->rMargin, 'top' => $this->tMargin, 'bottom' => $this->bMargin, 'header' => $this->header_margin, 'footer' => $this->footer_margin, 'cell' => $this->cMargin, ); return $ret; } /** * Returns an array containing original margins: * <ul> <li>$ret['left'] = left margin</li> <li>$ret['right'] = right margin</li> * </ul> * @return array containing all margins measures * @access public * @since 4.0.012 (2008-07-24) */ public function getOriginalMargins() { $ret = array( 'left' => $this->original_lMargin, 'right' => $this->original_rMargin ); return $ret; } /** * Returns the current font size. * @return current font size * @access public * @since 3.2.000 (2008-06-23) */ public function getFontSize() { return $this->FontSize; } /** * Returns the current font size in points unit. * @return current font size in points unit * @access public * @since 3.2.000 (2008-06-23) */ public function getFontSizePt() { return $this->FontSizePt; } /** * Returns the current font family name. * @return string current font family name * @access public * @since 4.3.008 (2008-12-05) */ public function getFontFamily() { return $this->FontFamily; } /** * Returns the current font style. * @return string current font style * @access public * @since 4.3.008 (2008-12-05) */ public function getFontStyle() { return $this->FontStyle; } /** * Extracts the CSS properties from a CSS string. * @param string $cssdata string containing CSS definitions. * @return An array where the keys are the CSS selectors and the values are the CSS properties. * @author Nicola Asuni * @since 5.1.000 (2010-05-25) * @access protected */ protected function extractCSSproperties($cssdata) { if (empty($cssdata)) { return array(); } // remove comments $cssdata = preg_replace('/\/\*[^\*]*\*\//', '', $cssdata); // remove newlines and multiple spaces $cssdata = preg_replace('/[\s]+/', ' ', $cssdata); // remove some spaces $cssdata = preg_replace('/[\s]*([;:\{\}]{1})[\s]*/', '\\1', $cssdata); // remove empty blocks $cssdata = preg_replace('/([^\}\{]+)\{\}/', '', $cssdata); // replace media type parenthesis $cssdata = preg_replace('/@media[\s]+([^\{]*)\{/i', '@media \\1§', $cssdata); $cssdata = preg_replace('/\}\}/si', '}§', $cssdata); // trim string $cssdata = trim($cssdata); // find media blocks (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv) $cssblocks = array(); $matches = array(); if (preg_match_all('/@media[\s]+([^\§]*)§([^§]*)§/i', $cssdata, $matches) > 0) { foreach ($matches[1] as $key => $type) { $cssblocks[$type] = $matches[2][$key]; } // remove media blocks $cssdata = preg_replace('/@media[\s]+([^\§]*)§([^§]*)§/i', '', $cssdata); } // keep 'all' and 'print' media, other media types are discarded if (isset($cssblocks['all']) AND !empty($cssblocks['all'])) { $cssdata .= $cssblocks['all']; } if (isset($cssblocks['print']) AND !empty($cssblocks['print'])) { $cssdata .= $cssblocks['print']; } // reset css blocks array $cssblocks = array(); $matches = array(); // explode css data string into array if (substr($cssdata, -1) == '}') { // remove last parethesis $cssdata = substr($cssdata, 0, -1); } $matches = explode('}', $cssdata); foreach ($matches as $key => $block) { // index 0 contains the CSS selector, index 1 contains CSS properties $cssblocks[$key] = explode('{', $block); if (!isset($cssblocks[$key][1])) { // remove empty definitions unset($cssblocks[$key]); } } // split groups of selectors (comma-separated list of selectors) foreach ($cssblocks as $key => $block) { if (strpos($block[0], ',') > 0) { $selectors = explode(',', $block[0]); foreach ($selectors as $sel) { $cssblocks[] = array(0 => trim($sel), 1 => $block[1]); } unset($cssblocks[$key]); } } // covert array to selector => properties $cssdata = array(); foreach ($cssblocks as $block) { $selector = $block[0]; // calculate selector's specificity $matches = array(); $a = 0; // the declaration is not from is a 'style' attribute $b = intval(preg_match_all('/[\#]/', $selector, $matches)); // number of ID attributes $c = intval(preg_match_all('/[\[\.]/', $selector, $matches)); // number of other attributes $c += intval(preg_match_all('/[\:]link|visited|hover|active|focus|target|lang|enabled|disabled|checked|indeterminate|root|nth|first|last|only|empty|contains|not/i', $selector, $matches)); // number of pseudo-classes $d = intval(preg_match_all('/[\>\+\~\s]{1}[a-zA-Z0-9\*]+/', ' '.$selector, $matches)); // number of element names $d += intval(preg_match_all('/[\:][\:]/', $selector, $matches)); // number of pseudo-elements $specificity = $a.$b.$c.$d; // add specificity to the beginning of the selector $cssdata[$specificity.' '.$selector] = $block[1]; } // sort selectors alphabetically to account for specificity ksort($cssdata, SORT_STRING); // return array return $cssdata; } /** * Returns true if the CSS selector is valid for the selected HTML tag * @param array $dom array of HTML tags and properties * @param int $key key of the current HTML tag * @param string $selector CSS selector string * @return true if the selector is valid, false otherwise * @access protected * @since 5.1.000 (2010-05-25) */ protected function isValidCSSSelectorForTag($dom, $key, $selector) { $valid = false; // value to be returned $tag = $dom[$key]['value']; $class = array(); if (isset($dom[$key]['attribute']['class']) AND !empty($dom[$key]['attribute']['class'])) { $class = explode(' ', strtolower($dom[$key]['attribute']['class'])); } $id = ''; if (isset($dom[$key]['attribute']['id']) AND !empty($dom[$key]['attribute']['id'])) { $id = strtolower($dom[$key]['attribute']['id']); } $selector = preg_replace('/([\>\+\~\s]{1})([\.]{1})([^\>\+\~\s]*)/si', '\\1*.\\3', $selector); $matches = array(); if (preg_match_all('/([\>\+\~\s]{1})([a-zA-Z0-9\*]+)([^\>\+\~\s]*)/si', $selector, $matches, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE) > 0) { $parentop = array_pop($matches[1]); $operator = $parentop[0]; $offset = $parentop[1]; $lasttag = array_pop($matches[2]); $lasttag = strtolower(trim($lasttag[0])); if (($lasttag == '*') OR ($lasttag == $tag)) { // the last element on selector is our tag or 'any tag' $attrib = array_pop($matches[3]); $attrib = strtolower(trim($attrib[0])); if (!empty($attrib)) { // check if matches class, id, attribute, pseudo-class or pseudo-element switch ($attrib{0}) { case '.': { // class if (in_array(substr($attrib, 1), $class)) { $valid = true; } break; } case '#': { // ID if (substr($attrib, 1) == $id) { $valid = true; } break; } case '[': { // attribute $attrmatch = array(); if (preg_match('/\[([a-zA-Z0-9]*)[\s]*([\~\^\$\*\|\=]*)[\s]*["]?([^"\]]*)["]?\]/i', $attrib, $attrmatch) > 0) { $att = strtolower($attrmatch[1]); $val = $attrmatch[3]; if (isset($dom[$key]['attribute'][$att])) { switch ($attrmatch[2]) { case '=': { if ($dom[$key]['attribute'][$att] == $val) { $valid = true; } break; } case '~=': { if (in_array($val, explode(' ', $dom[$key]['attribute'][$att]))) { $valid = true; } break; } case '^=': { if ($val == substr($dom[$key]['attribute'][$att], 0, strlen($val))) { $valid = true; } break; } case '$=': { if ($val == substr($dom[$key]['attribute'][$att], -strlen($val))) { $valid = true; } break; } case '*=': { if (strpos($dom[$key]['attribute'][$att], $val) !== false) { $valid = true; } break; } case '|=': { if ($dom[$key]['attribute'][$att] == $val) { $valid = true; } elseif (preg_match('/'.$val.'[\-]{1}/i', $dom[$key]['attribute'][$att]) > 0) { $valid = true; } break; } default: { $valid = true; } } } } break; } case ':': { // pseudo-class or pseudo-element if ($attrib{1} == ':') { // pseudo-element // pseudo-elements are not supported! // (::first-line, ::first-letter, ::before, ::after) } else { // pseudo-class // pseudo-classes are not supported! // (:root, :nth-child(n), :nth-last-child(n), :nth-of-type(n), :nth-last-of-type(n), :first-child, :last-child, :first-of-type, :last-of-type, :only-child, :only-of-type, :empty, :link, :visited, :active, :hover, :focus, :target, :lang(fr), :enabled, :disabled, :checked) } break; } } // end of switch } else { $valid = true; } if ($valid AND ($offset > 0)) { $valid = false; // check remaining selector part $selector = substr($selector, 0, $offset); switch ($operator) { case ' ': { // descendant of an element while ($dom[$key]['parent'] > 0) { if ($this->isValidCSSSelectorForTag($dom, $dom[$key]['parent'], $selector)) { $valid = true; break; } else { $key = $dom[$key]['parent']; } } break; } case '>': { // child of an element $valid = $this->isValidCSSSelectorForTag($dom, $dom[$key]['parent'], $selector); break; } case '+': { // immediately preceded by an element for ($i = ($key - 1); $i > $dom[$key]['parent']; --$i) { if ($dom[$i]['tag'] AND $dom[$i]['opening']) { $valid = $this->isValidCSSSelectorForTag($dom, $i, $selector); break; } } break; } case '~': { // preceded by an element for ($i = ($key - 1); $i > $dom[$key]['parent']; --$i) { if ($dom[$i]['tag'] AND $dom[$i]['opening']) { if ($this->isValidCSSSelectorForTag($dom, $i, $selector)) { break; } } } break; } } } } } return $valid; } /** * Returns the styles that apply for the selected HTML tag. * @param array $dom array of HTML tags and properties * @param int $key key of the current HTML tag * @param array $css array of CSS properties * @return string containing CSS properties * @access protected * @since 5.1.000 (2010-05-25) */ protected function getTagStyleFromCSS($dom, $key, $css) { $tagstyle = ''; // style to be returned // get all styles that apply foreach($css as $selector => $style) { // remove specificity $selector = substr($selector, strpos($selector, ' ')); // check if this selector apply to current tag if ($this->isValidCSSSelectorForTag($dom, $key, $selector)) { // apply style $tagstyle .= ';'.$style; } } if (isset($dom[$key]['attribute']['style'])) { // attach inline style (latest properties have high priority) $tagstyle .= ';'.$dom[$key]['attribute']['style']; } // remove multiple semicolons $tagstyle = preg_replace('/[;]+/', ';', $tagstyle); return $tagstyle; } /** * Returns the border width from CSS property * @param string $width border width * @return int with in user units * @access protected * @since 5.7.000 (2010-08-02) */ protected function getCSSBorderWidth($width) { if ($width == 'thin') { $width = (2 / $this->k); } elseif ($width == 'medium') { $width = (4 / $this->k); } elseif ($width == 'thick') { $width = (6 / $this->k); } else { $width = $this->getHTMLUnitToUnits($width, 1, 'px', false); } return $width; } /** * Returns the border dash style from CSS property * @param string $style border style to convert * @return int sash style (return -1 in case of none or hidden border) * @access protected * @since 5.7.000 (2010-08-02) */ protected function getCSSBorderDashStyle($style) { switch (strtolower($style)) { case 'none': case 'hidden': { $dash = -1; break; } case 'dotted': { $dash = 1; break; } case 'dashed': { $dash = 3; break; } case 'double': case 'groove': case 'ridge': case 'inset': case 'outset': case 'solid': default: { $dash = 0; break; } } return $dash; } /** * Returns the border style array from CSS border properties * @param string $cssborder border properties * @return array containing border properties * @access protected * @since 5.7.000 (2010-08-02) */ protected function getCSSBorderStyle($cssborder) { $bprop = preg_split('/[\s]+/', trim($cssborder)); $border = array(); // value to be returned switch (count($bprop)) { case 3: { $width = $bprop[0]; $style = $bprop[1]; $color = $bprop[2]; break; } case 2: { $width = 'medium'; $style = $bprop[0]; $color = $bprop[1]; break; } case 1: { $width = 'medium'; $style = $bprop[0]; $color = 'black'; break; } default: { $width = 'medium'; $style = 'solid'; $color = 'black'; break; } } if ($style == 'none') { return array(); } $border['cap'] = 'square'; $border['join'] = 'miter'; $border['dash'] = $this->getCSSBorderDashStyle($style); if ($border['dash'] < 0) { return array(); } $border['width'] = $this->getCSSBorderWidth($width); $border['color'] = $this->convertHTMLColorToDec($color); return $border; } /** * Returns the HTML DOM array. * <ul><li>$dom[$key]['tag'] = true if tag, false otherwise;</li><li>$dom[$key]['value'] = tag name or text;</li><li>$dom[$key]['opening'] = true if opening tag, false otherwise;</li><li>$dom[$key]['attribute'] = array of attributes (attribute name is the key);</li><li>$dom[$key]['style'] = array of style attributes (attribute name is the key);</li><li>$dom[$key]['parent'] = id of parent element;</li><li>$dom[$key]['fontname'] = font family name;</li><li>$dom[$key]['fontstyle'] = font style;</li><li>$dom[$key]['fontsize'] = font size in points;</li><li>$dom[$key]['bgcolor'] = RGB array of background color;</li><li>$dom[$key]['fgcolor'] = RGB array of foreground color;</li><li>$dom[$key]['width'] = width in pixels;</li><li>$dom[$key]['height'] = height in pixels;</li><li>$dom[$key]['align'] = text alignment;</li><li>$dom[$key]['cols'] = number of colums in table;</li><li>$dom[$key]['rows'] = number of rows in table;</li></ul> * @param string $html html code * @return array * @access protected * @since 3.2.000 (2008-06-20) */ protected function getHtmlDomArray($html) { // array of CSS styles ( selector => properties). $css = array(); // get CSS array defined at previous call $matches = array(); if (preg_match_all('/<cssarray>([^\<]*)<\/cssarray>/isU', $html, $matches) > 0) { if (isset($matches[1][0])) { $css = array_merge($css, unserialize($this->unhtmlentities($matches[1][0]))); } $html = preg_replace('/<cssarray>(.*?)<\/cssarray>/isU', '', $html); } // extract external CSS files $matches = array(); if (preg_match_all('/<link([^\>]*)>/isU', $html, $matches) > 0) { foreach ($matches[1] as $key => $link) { $type = array(); if (preg_match('/type[\s]*=[\s]*"text\/css"/', $link, $type)) { $type = array(); preg_match('/media[\s]*=[\s]*"([^"]*)"/', $link, $type); // get 'all' and 'print' media, other media types are discarded // (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv) if (empty($type) OR (isset($type[1]) AND (($type[1] == 'all') OR ($type[1] == 'print')))) { $type = array(); if (preg_match('/href[\s]*=[\s]*"([^"]*)"/', $link, $type) > 0) { // read CSS data file $cssdata = file_get_contents(trim($type[1])); $css = array_merge($css, $this->extractCSSproperties($cssdata)); } } } } } // extract style tags $matches = array(); if (preg_match_all('/<style([^\>]*)>([^\<]*)<\/style>/isU', $html, $matches) > 0) { foreach ($matches[1] as $key => $media) { $type = array(); preg_match('/media[\s]*=[\s]*"([^"]*)"/', $media, $type); // get 'all' and 'print' media, other media types are discarded // (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv) if (empty($type) OR (isset($type[1]) AND (($type[1] == 'all') OR ($type[1] == 'print')))) { $cssdata = $matches[2][$key]; $css = array_merge($css, $this->extractCSSproperties($cssdata)); } } } // create a special tag to contain the CSS array (used for table content) $csstagarray = '<cssarray>'.htmlentities(serialize($css)).'</cssarray>'; // remove head and style blocks $html = preg_replace('/<head([^\>]*)>(.*?)<\/head>/siU', '', $html); $html = preg_replace('/<style([^\>]*)>([^\<]*)<\/style>/isU', '', $html); // define block tags $blocktags = array('blockquote','br','dd','dl','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','pre','ul','tcpdf','table','tr','td'); // define self-closing tags $selfclosingtags = array('area','base','basefont','br','hr','input','img','link','meta'); // remove all unsupported tags (the line below lists all supported tags) $html = strip_tags($html, '<marker/><a><b><blockquote><body><br><br/><dd><del><div><dl><dt><em><font><form><h1><h2><h3><h4><h5><h6><hr><hr/><i><img><input><label><li><ol><option><p><pre><s><select><small><span><strike><strong><sub><sup><table><tablehead><tcpdf><td><textarea><th><thead><tr><tt><u><ul>'); //replace some blank characters $html = preg_replace('/<pre/', '<xre', $html); // preserve pre tag $html = preg_replace('/<(table|tr|td|th|tcpdf|blockquote|dd|div|dl|dt|form|h1|h2|h3|h4|h5|h6|br|hr|li|ol|ul|p)([^\>]*)>[\n\r\t]+/', '<\\1\\2>', $html); $html = preg_replace('@(\r\n|\r)@', "\n", $html); $repTable = array("\t" => ' ', "\0" => ' ', "\x0B" => ' ', "\\" => "\\\\"); $html = strtr($html, $repTable); $offset = 0; while (($offset < strlen($html)) AND ($pos = strpos($html, '</pre>', $offset)) !== false) { $html_a = substr($html, 0, $offset); $html_b = substr($html, $offset, ($pos - $offset + 6)); while (preg_match("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", $html_b)) { // preserve newlines on <pre> tag $html_b = preg_replace("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", "<xre\\1>\\2<br />\\3</pre>", $html_b); } while (preg_match("'<xre([^\>]*)>(.*?)".$this->re_space['p']."(.*?)</pre>'".$this->re_space['m'], $html_b)) { // preserve spaces on <pre> tag $html_b = preg_replace("'<xre([^\>]*)>(.*?)".$this->re_space['p']."(.*?)</pre>'".$this->re_space['m'], "<xre\\1>\\2&nbsp;\\3</pre>", $html_b); } $html = $html_a.$html_b.substr($html, $pos + 6); $offset = strlen($html_a.$html_b); } $offset = 0; while (($offset < strlen($html)) AND ($pos = strpos($html, '</textarea>', $offset)) !== false) { $html_a = substr($html, 0, $offset); $html_b = substr($html, $offset, ($pos - $offset + 11)); while (preg_match("'<textarea([^\>]*)>(.*?)\n(.*?)</textarea>'si", $html_b)) { // preserve newlines on <textarea> tag $html_b = preg_replace("'<textarea([^\>]*)>(.*?)\n(.*?)</textarea>'si", "<textarea\\1>\\2<TBR>\\3</textarea>", $html_b); $html_b = preg_replace("'<textarea([^\>]*)>(.*?)[\"](.*?)</textarea>'si", "<textarea\\1>\\2''\\3</textarea>", $html_b); } $html = $html_a.$html_b.substr($html, $pos + 11); $offset = strlen($html_a.$html_b); } $html = preg_replace('/([\s]*)<option/si', '<option', $html); $html = preg_replace('/<\/option>([\s]*)/si', '</option>', $html); $offset = 0; while (($offset < strlen($html)) AND ($pos = strpos($html, '</option>', $offset)) !== false) { $html_a = substr($html, 0, $offset); $html_b = substr($html, $offset, ($pos - $offset + 9)); while (preg_match("'<option([^\>]*)>(.*?)</option>'si", $html_b)) { $html_b = preg_replace("'<option([\s]+)value=\"([^\"]*)\"([^\>]*)>(.*?)</option>'si", "\\2#!TaB!#\\4#!NwL!#", $html_b); $html_b = preg_replace("'<option([^\>]*)>(.*?)</option>'si", "\\2#!NwL!#", $html_b); } $html = $html_a.$html_b.substr($html, $pos + 9); $offset = strlen($html_a.$html_b); } if (preg_match("'</select'si", $html)) { $html = preg_replace("'<select([^\>]*)>'si", "<select\\1 opt=\"", $html); $html = preg_replace("'#!NwL!#</select>'si", "\" />", $html); } $html = str_replace("\n", ' ', $html); // restore textarea newlines $html = str_replace('<TBR>', "\n", $html); // remove extra spaces from code $html = preg_replace('/[\s]+<\/(table|tr|ul|ol|dl)>/', '</\\1>', $html); $html = preg_replace('/'.$this->re_space['p'].'+<\/(td|th|li|dt|dd)>/'.$this->re_space['m'], '</\\1>', $html); $html = preg_replace('/[\s]+<(tr|td|th|li|dt|dd)/', '<\\1', $html); $html = preg_replace('/'.$this->re_space['p'].'+<(ul|ol|dl|br)/'.$this->re_space['m'], '<\\1', $html); $html = preg_replace('/<\/(table|tr|td|th|blockquote|dd|dt|dl|div|dt|h1|h2|h3|h4|h5|h6|hr|li|ol|ul|p)>[\s]+</', '</\\1><', $html); $html = preg_replace('/<\/(td|th)>/', '<marker style="font-size:0"/></\\1>', $html); $html = preg_replace('/<\/table>([\s]*)<marker style="font-size:0"\/>/', '</table>', $html); $html = preg_replace('/'.$this->re_space['p'].'+<img/'.$this->re_space['m'], chr(32).'<img', $html); $html = preg_replace('/<img([^\>]*)>/xi', '<img\\1><span><marker style="font-size:0"/></span>', $html); $html = preg_replace('/<xre/', '<pre', $html); // restore pre tag $html = preg_replace('/<textarea([^\>]*)>([^\<]*)<\/textarea>/xi', '<textarea\\1 value="\\2" />', $html); $html = preg_replace('/<li([^\>]*)><\/li>/', '<li\\1>&nbsp;</li>', $html); $html = preg_replace('/<li([^\>]*)>'.$this->re_space['p'].'*<img/'.$this->re_space['m'], '<li\\1><font size="1">&nbsp;</font><img', $html); $html = preg_replace('/<([^\>\/]*)>[\s]/', '<\\1>&nbsp;', $html); // preserve some spaces $html = preg_replace('/[\s]<\/([^\>]*)>/', '&nbsp;</\\1>', $html); // preserve some spaces $html = preg_replace('/'.$this->re_space['p'].'+/'.$this->re_space['m'], chr(32), $html); // replace multiple spaces with a single space // trim string $html = $this->stringTrim($html); // pattern for generic tag $tagpattern = '/(<[^>]+>)/'; // explodes the string $a = preg_split($tagpattern, $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); // count elements $maxel = count($a); $elkey = 0; $key = 0; // create an array of elements $dom = array(); $dom[$key] = array(); // set inheritable properties fot the first void element // possible inheritable properties are: azimuth, border-collapse, border-spacing, caption-side, color, cursor, direction, empty-cells, font, font-family, font-stretch, font-size, font-size-adjust, font-style, font-variant, font-weight, letter-spacing, line-height, list-style, list-style-image, list-style-position, list-style-type, orphans, page, page-break-inside, quotes, speak, speak-header, text-align, text-indent, text-transform, volume, white-space, widows, word-spacing $dom[$key]['tag'] = false; $dom[$key]['block'] = false; $dom[$key]['value'] = ''; $dom[$key]['parent'] = 0; $dom[$key]['fontname'] = $this->FontFamily; $dom[$key]['fontstyle'] = $this->FontStyle; $dom[$key]['fontsize'] = $this->FontSizePt; $dom[$key]['stroke'] = $this->textstrokewidth; $dom[$key]['fill'] = (($this->textrendermode % 2) == 0); $dom[$key]['clip'] = ($this->textrendermode > 3); $dom[$key]['line-height'] = $this->cell_height_ratio; $dom[$key]['bgcolor'] = false; $dom[$key]['fgcolor'] = $this->fgcolor; // color $dom[$key]['strokecolor'] = $this->strokecolor; $dom[$key]['align'] = ''; $dom[$key]['listtype'] = ''; $dom[$key]['text-indent'] = 0; $dom[$key]['border'] = array(); $thead = false; // true when we are inside the THEAD tag ++$key; $level = array(); array_push($level, 0); // root while ($elkey < $maxel) { $dom[$key] = array(); $element = $a[$elkey]; $dom[$key]['elkey'] = $elkey; if (preg_match($tagpattern, $element)) { // html tag $element = substr($element, 1, -1); // get tag name preg_match('/[\/]?([a-zA-Z0-9]*)/', $element, $tag); $tagname = strtolower($tag[1]); // check if we are inside a table header if ($tagname == 'thead') { if ($element{0} == '/') { $thead = false; } else { $thead = true; } ++$elkey; continue; } $dom[$key]['tag'] = true; $dom[$key]['value'] = $tagname; if (in_array($dom[$key]['value'], $blocktags)) { $dom[$key]['block'] = true; } else { $dom[$key]['block'] = false; } if ($element{0} == '/') { // *** closing html tag $dom[$key]['opening'] = false; $dom[$key]['parent'] = end($level); array_pop($level); $dom[$key]['fontname'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontname']; $dom[$key]['fontstyle'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontstyle']; $dom[$key]['fontsize'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontsize']; $dom[$key]['stroke'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['stroke']; $dom[$key]['fill'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fill']; $dom[$key]['clip'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['clip']; $dom[$key]['line-height'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['line-height']; $dom[$key]['bgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['bgcolor']; $dom[$key]['fgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fgcolor']; $dom[$key]['strokecolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['strokecolor']; $dom[$key]['align'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['align']; if (isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'])) { $dom[$key]['listtype'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype']; } // set the number of columns in table tag if (($dom[$key]['value'] == 'tr') AND (!isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['cols']))) { $dom[($dom[($dom[$key]['parent'])]['parent'])]['cols'] = $dom[($dom[$key]['parent'])]['cols']; } if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) { $dom[($dom[$key]['parent'])]['content'] = $csstagarray; for ($i = ($dom[$key]['parent'] + 1); $i < $key; ++$i) { $dom[($dom[$key]['parent'])]['content'] .= $a[$dom[$i]['elkey']]; } $key = $i; $parent_table = $dom[$dom[$dom[($dom[$key]['parent'])]['parent']]['parent']]; $parent_padding = 0; $parent_spacing = 0; if (isset($parent_table['attribute']['cellpadding'])) { $parent_padding = $this->getHTMLUnitToUnits($parent_table['attribute']['cellpadding'], 1, 'px'); } if (isset($parent_table['attribute']['cellspacing'])) { $parent_spacing = $this->getHTMLUnitToUnits($parent_table['attribute']['cellspacing'], 1, 'px'); } // mark nested tables $dom[($dom[$key]['parent'])]['content'] = str_replace('<table', '<table nested="true" pcellpadding="'.$parent_padding.'" pcellspacing="'.$parent_spacing.'"', $dom[($dom[$key]['parent'])]['content']); // remove thead sections from nested tables $dom[($dom[$key]['parent'])]['content'] = str_replace('<thead>', '', $dom[($dom[$key]['parent'])]['content']); $dom[($dom[$key]['parent'])]['content'] = str_replace('</thead>', '', $dom[($dom[$key]['parent'])]['content']); } // store header rows on a new table if (($dom[$key]['value'] == 'tr') AND ($dom[($dom[$key]['parent'])]['thead'] === true)) { if ($this->empty_string($dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'])) { $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] = $a[$dom[($dom[($dom[$key]['parent'])]['parent'])]['elkey']]; } for ($i = $dom[$key]['parent']; $i <= $key; ++$i) { $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] .= $a[$dom[$i]['elkey']]; } if (!isset($dom[($dom[$key]['parent'])]['attribute'])) { $dom[($dom[$key]['parent'])]['attribute'] = array(); } // header elements must be always contained in a single page $dom[($dom[$key]['parent'])]['attribute']['nobr'] = 'true'; } if (($dom[$key]['value'] == 'table') AND (!$this->empty_string($dom[($dom[$key]['parent'])]['thead']))) { // remove the nobr attributes from the table header $dom[($dom[$key]['parent'])]['thead'] = str_replace(' nobr="true"', '', $dom[($dom[$key]['parent'])]['thead']); $dom[($dom[$key]['parent'])]['thead'] .= '</tablehead>'; } } else { // *** opening or self-closing html tag $dom[$key]['opening'] = true; $dom[$key]['parent'] = end($level); if ((substr($element, -1, 1) == '/') OR (in_array($dom[$key]['value'], $selfclosingtags))) { // self-closing tag $dom[$key]['self'] = true; } else { // opening tag array_push($level, $key); $dom[$key]['self'] = false; } // copy some values from parent $parentkey = 0; if ($key > 0) { $parentkey = $dom[$key]['parent']; $dom[$key]['fontname'] = $dom[$parentkey]['fontname']; $dom[$key]['fontstyle'] = $dom[$parentkey]['fontstyle']; $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize']; $dom[$key]['stroke'] = $dom[$parentkey]['stroke']; $dom[$key]['fill'] = $dom[$parentkey]['fill']; $dom[$key]['clip'] = $dom[$parentkey]['clip']; $dom[$key]['line-height'] = $dom[$parentkey]['line-height']; $dom[$key]['bgcolor'] = $dom[$parentkey]['bgcolor']; $dom[$key]['fgcolor'] = $dom[$parentkey]['fgcolor']; $dom[$key]['strokecolor'] = $dom[$parentkey]['strokecolor']; $dom[$key]['align'] = $dom[$parentkey]['align']; $dom[$key]['listtype'] = $dom[$parentkey]['listtype']; $dom[$key]['text-indent'] = $dom[$parentkey]['text-indent']; $dom[$key]['border'] = array(); } // get attributes preg_match_all('/([^=\s]*)[\s]*=[\s]*"([^"]*)"/', $element, $attr_array, PREG_PATTERN_ORDER); $dom[$key]['attribute'] = array(); // reset attribute array while (list($id, $name) = each($attr_array[1])) { $dom[$key]['attribute'][strtolower($name)] = $attr_array[2][$id]; } if (!empty($css)) { // merge eternal CSS style to current style $dom[$key]['attribute']['style'] = $this->getTagStyleFromCSS($dom, $key, $css); } // split style attributes if (isset($dom[$key]['attribute']['style']) AND !empty($dom[$key]['attribute']['style'])) { // get style attributes preg_match_all('/([^;:\s]*):([^;]*)/', $dom[$key]['attribute']['style'], $style_array, PREG_PATTERN_ORDER); $dom[$key]['style'] = array(); // reset style attribute array while (list($id, $name) = each($style_array[1])) { // in case of duplicate attribute the last replace the previous $dom[$key]['style'][strtolower($name)] = trim($style_array[2][$id]); } // --- get some style attributes --- if (isset($dom[$key]['style']['font-family'])) { // font family if (isset($dom[$key]['style']['font-family'])) { $dom[$key]['fontname'] = $this->getFontFamilyName($dom[$key]['style']['font-family']); } } // list-style-type if (isset($dom[$key]['style']['list-style-type'])) { $dom[$key]['listtype'] = trim(strtolower($dom[$key]['style']['list-style-type'])); if ($dom[$key]['listtype'] == 'inherit') { $dom[$key]['listtype'] = $dom[$parentkey]['listtype']; } } // text-indent if (isset($dom[$key]['style']['text-indent'])) { $dom[$key]['text-indent'] = $this->getHTMLUnitToUnits($dom[$key]['style']['text-indent']); if ($dom[$key]['text-indent'] == 'inherit') { $dom[$key]['text-indent'] = $dom[$parentkey]['text-indent']; } } // font size if (isset($dom[$key]['style']['font-size'])) { $fsize = trim($dom[$key]['style']['font-size']); switch ($fsize) { // absolute-size case 'xx-small': { $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 4; break; } case 'x-small': { $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 3; break; } case 'small': { $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 2; break; } case 'medium': { $dom[$key]['fontsize'] = $dom[0]['fontsize']; break; } case 'large': { $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 2; break; } case 'x-large': { $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 4; break; } case 'xx-large': { $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 6; break; } // relative-size case 'smaller': { $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'] - 3; break; } case 'larger': { $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'] + 3; break; } default: { $dom[$key]['fontsize'] = $this->getHTMLUnitToUnits($fsize, $dom[$parentkey]['fontsize'], 'pt', true); } } } // line-height if (isset($dom[$key]['style']['line-height'])) { $lineheight = trim($dom[$key]['style']['line-height']); switch ($lineheight) { // A normal line height. This is default case 'normal': { $dom[$key]['line-height'] = $dom[0]['line-height']; break; } default: { if (is_numeric($lineheight)) { $lineheight = $lineheight * 100; } $dom[$key]['line-height'] = $this->getHTMLUnitToUnits($lineheight, 1, '%', true); } } } // font style if (isset($dom[$key]['style']['font-weight']) AND (strtolower($dom[$key]['style']['font-weight']{0}) == 'b')) { $dom[$key]['fontstyle'] .= 'B'; } if (isset($dom[$key]['style']['font-style']) AND (strtolower($dom[$key]['style']['font-style']{0}) == 'i')) { $dom[$key]['fontstyle'] .= 'I'; } // font color if (isset($dom[$key]['style']['color']) AND (!$this->empty_string($dom[$key]['style']['color']))) { $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['color']); } elseif ($dom[$key]['value'] == 'a') { $dom[$key]['fgcolor'] = $this->htmlLinkColorArray; } // background color if (isset($dom[$key]['style']['background-color']) AND (!$this->empty_string($dom[$key]['style']['background-color']))) { $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['background-color']); } // text-decoration if (isset($dom[$key]['style']['text-decoration'])) { $decors = explode(' ', strtolower($dom[$key]['style']['text-decoration'])); foreach ($decors as $dec) { $dec = trim($dec); if (!$this->empty_string($dec)) { if ($dec{0} == 'u') { // underline $dom[$key]['fontstyle'] .= 'U'; } elseif ($dec{0} == 'l') { // line-trough $dom[$key]['fontstyle'] .= 'D'; } elseif ($dec{0} == 'o') { // overline $dom[$key]['fontstyle'] .= 'O'; } } } } elseif ($dom[$key]['value'] == 'a') { $dom[$key]['fontstyle'] = $this->htmlLinkFontStyle; } // check for width attribute if (isset($dom[$key]['style']['width'])) { $dom[$key]['width'] = $dom[$key]['style']['width']; } // check for height attribute if (isset($dom[$key]['style']['height'])) { $dom[$key]['height'] = $dom[$key]['style']['height']; } // check for text alignment if (isset($dom[$key]['style']['text-align'])) { $dom[$key]['align'] = strtoupper($dom[$key]['style']['text-align']{0}); } // check for CSS border properties if (isset($dom[$key]['style']['border'])) { $borderstyle = $this->getCSSBorderStyle($dom[$key]['style']['border']); if (!empty($borderstyle)) { $dom[$key]['border']['LTRB'] = $borderstyle; } } if (isset($dom[$key]['style']['border-color'])) { $brd_colors = preg_split('/[\s]+/', trim($dom[$key]['style']['border-color'])); if (isset($brd_colors[3])) { $dom[$key]['border']['L']['color'] = $this->convertHTMLColorToDec($brd_colors[3]); } if (isset($brd_colors[1])) { $dom[$key]['border']['R']['color'] = $this->convertHTMLColorToDec($brd_colors[1]); } if (isset($brd_colors[0])) { $dom[$key]['border']['T']['color'] = $this->convertHTMLColorToDec($brd_colors[0]); } if (isset($brd_colors[2])) { $dom[$key]['border']['B']['color'] = $this->convertHTMLColorToDec($brd_colors[2]); } } if (isset($dom[$key]['style']['border-width'])) { $brd_widths = preg_split('/[\s]+/', trim($dom[$key]['style']['border-width'])); if (isset($brd_widths[3])) { $dom[$key]['border']['L']['width'] = $this->getCSSBorderWidth($brd_widths[3]); } if (isset($brd_widths[1])) { $dom[$key]['border']['R']['width'] = $this->getCSSBorderWidth($brd_widths[1]); } if (isset($brd_widths[0])) { $dom[$key]['border']['T']['width'] = $this->getCSSBorderWidth($brd_widths[0]); } if (isset($brd_widths[2])) { $dom[$key]['border']['B']['width'] = $this->getCSSBorderWidth($brd_widths[2]); } } if (isset($dom[$key]['style']['border-style'])) { $brd_styles = preg_split('/[\s]+/', trim($dom[$key]['style']['border-style'])); if (isset($brd_styles[3])) { $dom[$key]['border']['L']['cap'] = 'square'; $dom[$key]['border']['L']['join'] = 'miter'; $dom[$key]['border']['L']['dash'] = $this->getCSSBorderDashStyle($brd_styles[3]); if ($dom[$key]['border']['L']['dash'] < 0) { $dom[$key]['border']['L'] = array(); } } if (isset($brd_styles[1])) { $dom[$key]['border']['R']['cap'] = 'square'; $dom[$key]['border']['R']['join'] = 'miter'; $dom[$key]['border']['R']['dash'] = $this->getCSSBorderDashStyle($brd_styles[1]); if ($dom[$key]['border']['R']['dash'] < 0) { $dom[$key]['border']['R'] = array(); } } if (isset($brd_styles[0])) { $dom[$key]['border']['T']['cap'] = 'square'; $dom[$key]['border']['T']['join'] = 'miter'; $dom[$key]['border']['T']['dash'] = $this->getCSSBorderDashStyle($brd_styles[0]); if ($dom[$key]['border']['T']['dash'] < 0) { $dom[$key]['border']['T'] = array(); } } if (isset($brd_styles[2])) { $dom[$key]['border']['B']['cap'] = 'square'; $dom[$key]['border']['B']['join'] = 'miter'; $dom[$key]['border']['B']['dash'] = $this->getCSSBorderDashStyle($brd_styles[2]); if ($dom[$key]['border']['B']['dash'] < 0) { $dom[$key]['border']['B'] = array(); } } } $borderside = array('L' => 'left', 'R' => 'right', 'T' => 'top', 'B' => 'bottom'); foreach ($borderside as $bsk => $bsv) { if (isset($dom[$key]['style']['border-'.$bsv])) { $borderstyle = $this->getCSSBorderStyle($dom[$key]['style']['border-'.$bsv]); if (!empty($borderstyle)) { $dom[$key]['border'][$bsk] = $borderstyle; } } if (isset($dom[$key]['style']['border-'.$bsv.'-color'])) { $dom[$key]['border'][$bsk]['color'] = $this->convertHTMLColorToDec($dom[$key]['style']['border-'.$bsv.'-color']); } if (isset($dom[$key]['style']['border-'.$bsv.'-width'])) { $dom[$key]['border'][$bsk]['width'] = $this->getCSSBorderWidth($dom[$key]['style']['border-'.$bsv.'-width']); } if (isset($dom[$key]['style']['border-'.$bsv.'-style'])) { $dom[$key]['border'][$bsk]['dash'] = $this->getCSSBorderDashStyle($dom[$key]['style']['border-'.$bsv.'-style']); if ($dom[$key]['border'][$bsk]['dash'] < 0) { $dom[$key]['border'][$bsk] = array(); } } } // page-break-inside if (isset($dom[$key]['style']['page-break-inside']) AND ($dom[$key]['style']['page-break-inside'] == 'avoid')) { $dom[$key]['attribute']['nobr'] = 'true'; } // page-break-before if (isset($dom[$key]['style']['page-break-before'])) { if ($dom[$key]['style']['page-break-before'] == 'always') { $dom[$key]['attribute']['pagebreak'] = 'true'; } elseif ($dom[$key]['style']['page-break-before'] == 'left') { $dom[$key]['attribute']['pagebreak'] = 'left'; } elseif ($dom[$key]['style']['page-break-before'] == 'right') { $dom[$key]['attribute']['pagebreak'] = 'right'; } } // page-break-after if (isset($dom[$key]['style']['page-break-after'])) { if ($dom[$key]['style']['page-break-after'] == 'always') { $dom[$key]['attribute']['pagebreakafter'] = 'true'; } elseif ($dom[$key]['style']['page-break-after'] == 'left') { $dom[$key]['attribute']['pagebreakafter'] = 'left'; } elseif ($dom[$key]['style']['page-break-after'] == 'right') { $dom[$key]['attribute']['pagebreakafter'] = 'right'; } } } if (isset($dom[$key]['attribute']['border']) AND ($dom[$key]['attribute']['border'] != 0)) { $borderstyle = $this->getCSSBorderStyle($dom[$key]['attribute']['border'].' solid black'); if (!empty($borderstyle)) { $dom[$key]['border']['LTRB'] = $borderstyle; } } // check for font tag if ($dom[$key]['value'] == 'font') { // font family if (isset($dom[$key]['attribute']['face'])) { $dom[$key]['fontname'] = $this->getFontFamilyName($dom[$key]['attribute']['face']); } // font size if (isset($dom[$key]['attribute']['size'])) { if ($key > 0) { if ($dom[$key]['attribute']['size']{0} == '+') { $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] + intval(substr($dom[$key]['attribute']['size'], 1)); } elseif ($dom[$key]['attribute']['size']{0} == '-') { $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] - intval(substr($dom[$key]['attribute']['size'], 1)); } else { $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']); } } else { $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']); } } } // force natural alignment for lists if ((($dom[$key]['value'] == 'ul') OR ($dom[$key]['value'] == 'ol') OR ($dom[$key]['value'] == 'dl')) AND (!isset($dom[$key]['align']) OR $this->empty_string($dom[$key]['align']) OR ($dom[$key]['align'] != 'J'))) { if ($this->rtl) { $dom[$key]['align'] = 'R'; } else { $dom[$key]['align'] = 'L'; } } if (($dom[$key]['value'] == 'small') OR ($dom[$key]['value'] == 'sup') OR ($dom[$key]['value'] == 'sub')) { if (!isset($dom[$key]['attribute']['size']) AND !isset($dom[$key]['style']['font-size'])) { $dom[$key]['fontsize'] = $dom[$key]['fontsize'] * K_SMALL_RATIO; } } if (($dom[$key]['value'] == 'strong') OR ($dom[$key]['value'] == 'b')) { $dom[$key]['fontstyle'] .= 'B'; } if (($dom[$key]['value'] == 'em') OR ($dom[$key]['value'] == 'i')) { $dom[$key]['fontstyle'] .= 'I'; } if ($dom[$key]['value'] == 'u') { $dom[$key]['fontstyle'] .= 'U'; } if (($dom[$key]['value'] == 'del') OR ($dom[$key]['value'] == 's') OR ($dom[$key]['value'] == 'strike')) { $dom[$key]['fontstyle'] .= 'D'; } if (!isset($dom[$key]['style']['text-decoration']) AND ($dom[$key]['value'] == 'a')) { $dom[$key]['fontstyle'] = $this->htmlLinkFontStyle; } if (($dom[$key]['value'] == 'pre') OR ($dom[$key]['value'] == 'tt')) { $dom[$key]['fontname'] = $this->default_monospaced_font; } if (($dom[$key]['value']{0} == 'h') AND (intval($dom[$key]['value']{1}) > 0) AND (intval($dom[$key]['value']{1}) < 7)) { // headings h1, h2, h3, h4, h5, h6 if (!isset($dom[$key]['attribute']['size']) AND !isset($dom[$key]['style']['font-size'])) { $headsize = (4 - intval($dom[$key]['value']{1})) * 2; $dom[$key]['fontsize'] = $dom[0]['fontsize'] + $headsize; } if (!isset($dom[$key]['style']['font-weight'])) { $dom[$key]['fontstyle'] .= 'B'; } } if (($dom[$key]['value'] == 'table')) { $dom[$key]['rows'] = 0; // number of rows $dom[$key]['trids'] = array(); // IDs of TR elements $dom[$key]['thead'] = ''; // table header rows } if (($dom[$key]['value'] == 'tr')) { $dom[$key]['cols'] = 0; if ($thead) { $dom[$key]['thead'] = true; // rows on thead block are printed as a separate table } else { $dom[$key]['thead'] = false; // store the number of rows on table element ++$dom[($dom[$key]['parent'])]['rows']; // store the TR elements IDs on table element array_push($dom[($dom[$key]['parent'])]['trids'], $key); } } if (($dom[$key]['value'] == 'th') OR ($dom[$key]['value'] == 'td')) { if (isset($dom[$key]['attribute']['colspan'])) { $colspan = intval($dom[$key]['attribute']['colspan']); } else { $colspan = 1; } $dom[$key]['attribute']['colspan'] = $colspan; $dom[($dom[$key]['parent'])]['cols'] += $colspan; } // set foreground color attribute if (isset($dom[$key]['attribute']['color']) AND (!$this->empty_string($dom[$key]['attribute']['color']))) { $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['color']); } elseif (!isset($dom[$key]['style']['color']) AND ($dom[$key]['value'] == 'a')) { $dom[$key]['fgcolor'] = $this->htmlLinkColorArray; } // set background color attribute if (isset($dom[$key]['attribute']['bgcolor']) AND (!$this->empty_string($dom[$key]['attribute']['bgcolor']))) { $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['bgcolor']); } // set stroke color attribute if (isset($dom[$key]['attribute']['strokecolor']) AND (!$this->empty_string($dom[$key]['attribute']['strokecolor']))) { $dom[$key]['strokecolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['strokecolor']); } // check for width attribute if (isset($dom[$key]['attribute']['width'])) { $dom[$key]['width'] = $dom[$key]['attribute']['width']; } // check for height attribute if (isset($dom[$key]['attribute']['height'])) { $dom[$key]['height'] = $dom[$key]['attribute']['height']; } // check for text alignment if (isset($dom[$key]['attribute']['align']) AND (!$this->empty_string($dom[$key]['attribute']['align'])) AND ($dom[$key]['value'] !== 'img')) { $dom[$key]['align'] = strtoupper($dom[$key]['attribute']['align']{0}); } // check for text rendering mode (the following attributes do not exist in HTML) if (isset($dom[$key]['attribute']['stroke'])) { // font stroke width $dom[$key]['stroke'] = $this->getHTMLUnitToUnits($dom[$key]['attribute']['stroke'], $dom[$key]['fontsize'], 'pt', true); } if (isset($dom[$key]['attribute']['fill'])) { // font fill if ($dom[$key]['attribute']['fill'] == 'true') { $dom[$key]['fill'] = true; } else { $dom[$key]['fill'] = false; } } if (isset($dom[$key]['attribute']['clip'])) { // clipping mode if ($dom[$key]['attribute']['clip'] == 'true') { $dom[$key]['clip'] = true; } else { $dom[$key]['clip'] = false; } } } // end opening tag } else { // text $dom[$key]['tag'] = false; $dom[$key]['block'] = false; $element = str_replace('$nbsp;', $this->unichr(160), $element); $dom[$key]['value'] = stripslashes($this->unhtmlentities($element)); $dom[$key]['parent'] = end($level); } ++$elkey; ++$key; } return $dom; } /** * Returns the string used to find spaces * @return string * @access protected * @author Nicola Asuni * @since 4.8.024 (2010-01-15) */ protected function getSpaceString() { $spacestr = chr(32); if ($this->isUnicodeFont()) { $spacestr = chr(0).chr(32); } return $spacestr; } /** * Prints a cell (rectangular area) with optional borders, background color and html text string. * The upper-left corner of the cell corresponds to the current position. After the call, the current position moves to the right or to the next line.<br /> * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting. * @param float $w Cell width. If 0, the cell extends up to the right margin. * @param float $h Cell minimum height. The cell extends automatically if needed. * @param float $x upper-left corner X coordinate * @param float $y upper-left corner Y coordinate * @param string $html html text to print. Default value: empty string. * @param mixed $border Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0))) * @param int $ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL language)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul> Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0. * @param boolean $fill Indicates if the cell background must be painted (true) or transparent (false). * @param boolean $reseth if true reset the last cell height (default true). * @param string $align Allows to center or align the text. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul> * @param boolean $autopadding if true, uses internal padding and automatically adjust it to account for line width. * @access public * @uses MultiCell() * @see Multicell(), writeHTML() */ public function writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=false, $reseth=true, $align='', $autopadding=true) { return $this->MultiCell($w, $h, $html, $border, $align, $fill, $ln, $x, $y, $reseth, 0, true, $autopadding, 0); } /** * Allows to preserve some HTML formatting (limited support).<br /> * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting. * Supported tags are: a, b, blockquote, br, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, img, li, ol, p, pre, small, span, strong, sub, sup, table, tcpdf, td, th, thead, tr, tt, u, ul * @param string $html text to display * @param boolean $ln if true add a new line after text (default = true) * @param boolean $fill Indicates if the background must be painted (true) or transparent (false). * @param boolean $reseth if true reset the last cell height (default false). * @param boolean $cell if true add the default cMargin space to each Write (default false). * @param string $align Allows to center or align the text. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul> * @access public */ public function writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='') { $gvars = $this->getGraphicVars(); // store current values $prevPage = $this->page; $prevlMargin = $this->lMargin; $prevrMargin = $this->rMargin; $curfontname = $this->FontFamily; $curfontstyle = $this->FontStyle; $curfontsize = $this->FontSizePt; $curfontascent = $this->getFontAscent($curfontname, $curfontstyle, $curfontsize); $curfontdescent = $this->getFontDescent($curfontname, $curfontstyle, $curfontsize); $this->newline = true; $newline = true; $startlinepage = $this->page; $minstartliney = $this->y; $maxbottomliney = 0; $startlinex = $this->x; $startliney = $this->y; $yshift = 0; $loop = 0; $curpos = 0; $this_method_vars = array(); $undo = false; $fontaligned = false; $this->premode = false; if (isset($this->PageAnnots[$this->page])) { $pask = count($this->PageAnnots[$this->page]); } else { $pask = 0; } if (!$this->InFooter) { if (isset($this->footerlen[$this->page])) { $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page]; } else { $this->footerpos[$this->page] = $this->pagelen[$this->page]; } $startlinepos = $this->footerpos[$this->page]; } else { $startlinepos = $this->pagelen[$this->page]; } $lalign = $align; $plalign = $align; if ($this->rtl) { $w = $this->x - $this->lMargin; } else { $w = $this->w - $this->rMargin - $this->x; } $w -= (2 * $this->cMargin); if ($cell) { if ($this->rtl) { $this->x -= $this->cMargin; $this->lMargin += $this->cMargin; } else { $this->x += $this->cMargin; $this->rMargin += $this->cMargin; } } if ($this->customlistindent >= 0) { $this->listindent = $this->customlistindent; } else { $this->listindent = $this->GetStringWidth('0000'); } $this->listindentlevel = 0; // save previous states $prev_cell_height_ratio = $this->cell_height_ratio; $prev_listnum = $this->listnum; $prev_listordered = $this->listordered; $prev_listcount = $this->listcount; $prev_lispacer = $this->lispacer; $this->listnum = 0; $this->listordered = array(); $this->listcount = array(); $this->lispacer = ''; if (($this->empty_string($this->lasth)) OR ($reseth)) { //set row height $this->lasth = $this->FontSize * $this->cell_height_ratio; } $dom = $this->getHtmlDomArray($html); $maxel = count($dom); $key = 0; while ($key < $maxel) { if ($dom[$key]['tag'] AND isset($dom[$key]['attribute']['pagebreak'])) { // check for pagebreak if (($dom[$key]['attribute']['pagebreak'] == 'true') OR ($dom[$key]['attribute']['pagebreak'] == 'left') OR ($dom[$key]['attribute']['pagebreak'] == 'right')) { // add a page (or trig AcceptPageBreak() for multicolumn mode) $this->checkPageBreak($this->PageBreakTrigger + 1); } if ((($dom[$key]['attribute']['pagebreak'] == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0)))) OR (($dom[$key]['attribute']['pagebreak'] == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) { // add a page (or trig AcceptPageBreak() for multicolumn mode) $this->checkPageBreak($this->PageBreakTrigger + 1); } } if ($dom[$key]['tag'] AND $dom[$key]['opening'] AND isset($dom[$key]['attribute']['nobr']) AND ($dom[$key]['attribute']['nobr'] == 'true')) { if (isset($dom[($dom[$key]['parent'])]['attribute']['nobr']) AND ($dom[($dom[$key]['parent'])]['attribute']['nobr'] == 'true')) { $dom[$key]['attribute']['nobr'] = false; } else { // store current object $this->startTransaction(); // save this method vars $this_method_vars['html'] = $html; $this_method_vars['ln'] = $ln; $this_method_vars['fill'] = $fill; $this_method_vars['reseth'] = $reseth; $this_method_vars['cell'] = $cell; $this_method_vars['align'] = $align; $this_method_vars['gvars'] = $gvars; $this_method_vars['prevPage'] = $prevPage; $this_method_vars['prevlMargin'] = $prevlMargin; $this_method_vars['prevrMargin'] = $prevrMargin; $this_method_vars['curfontname'] = $curfontname; $this_method_vars['curfontstyle'] = $curfontstyle; $this_method_vars['curfontsize'] = $curfontsize; $this_method_vars['curfontascent'] = $curfontascent; $this_method_vars['curfontdescent'] = $curfontdescent; $this_method_vars['minstartliney'] = $minstartliney; $this_method_vars['maxbottomliney'] = $maxbottomliney; $this_method_vars['yshift'] = $yshift; $this_method_vars['startlinepage'] = $startlinepage; $this_method_vars['startlinepos'] = $startlinepos; $this_method_vars['startlinex'] = $startlinex; $this_method_vars['startliney'] = $startliney; $this_method_vars['newline'] = $newline; $this_method_vars['loop'] = $loop; $this_method_vars['curpos'] = $curpos; $this_method_vars['pask'] = $pask; $this_method_vars['lalign'] = $lalign; $this_method_vars['plalign'] = $plalign; $this_method_vars['w'] = $w; $this_method_vars['prev_cell_height_ratio'] = $prev_cell_height_ratio; $this_method_vars['prev_listnum'] = $prev_listnum; $this_method_vars['prev_listordered'] = $prev_listordered; $this_method_vars['prev_listcount'] = $prev_listcount; $this_method_vars['prev_lispacer'] = $prev_lispacer; $this_method_vars['fontaligned'] = $fontaligned; $this_method_vars['key'] = $key; $this_method_vars['dom'] = $dom; } } // print THEAD block if (($dom[$key]['value'] == 'tr') AND isset($dom[$key]['thead']) AND $dom[$key]['thead']) { if (isset($dom[$key]['parent']) AND isset($dom[$dom[$key]['parent']]['thead']) AND !$this->empty_string($dom[$dom[$key]['parent']]['thead'])) { $this->inthead = true; // print table header (thead) $this->writeHTML($this->thead, false, false, false, false, ''); if (($this->start_transaction_page == ($this->numpages - 1)) OR ($this->y < $this->start_transaction_y) OR ($this->checkPageBreak($this->lasth, '', false))) { // restore previous object $this->rollbackTransaction(true); // restore previous values foreach ($this_method_vars as $vkey => $vval) { $$vkey = $vval; } // disable table header $tmp_thead = $this->thead; $this->thead = ''; // add a page (or trig AcceptPageBreak() for multicolumn mode) $pre_y = $this->y; if ((!$this->checkPageBreak($this->PageBreakTrigger + 1)) AND ($this->y < $pre_y)) { // fix for multicolumn mode $startliney = $this->y; } $this->start_transaction_page = $this->page; $this->start_transaction_y = $this->y; // restore table header $this->thead = $tmp_thead; // fix table border properties if (isset($dom[$dom[$key]['parent']]['attribute']['cellspacing'])) { $tmp_cellspacing = $this->getHTMLUnitToUnits($dom[$dom[$key]['parent']]['attribute']['cellspacing'], 1, 'px'); } else { $tmp_cellspacing = 0; } $dom[$dom[$key]['parent']]['borderposition']['page'] = $this->page; $dom[$dom[$key]['parent']]['borderposition']['column'] = $this->current_column; $dom[$dom[$key]['parent']]['borderposition']['y'] = $this->y + $tmp_cellspacing; $xoffset = ($this->x - $dom[$dom[$key]['parent']]['borderposition']['x']); $dom[$dom[$key]['parent']]['borderposition']['x'] += $xoffset; $dom[$dom[$key]['parent']]['borderposition']['xmax'] += $xoffset; // print table header (thead) $this->writeHTML($this->thead, false, false, false, false, ''); } } // move $key index forward to skip THEAD block while ( ($key < $maxel) AND (!( ($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'tr') AND (!isset($dom[$key]['thead']) OR !$dom[$key]['thead'])) OR ($dom[$key]['tag'] AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == 'table'))) )) { ++$key; } } if ($dom[$key]['tag'] OR ($key == 0)) { if ((($dom[$key]['value'] == 'table') OR ($dom[$key]['value'] == 'tr')) AND (isset($dom[$key]['align']))) { $dom[$key]['align'] = ($this->rtl) ? 'R' : 'L'; } // vertically align image in line if ((!$this->newline) AND ($dom[$key]['value'] == 'img') AND (isset($dom[$key]['height'])) AND ($dom[$key]['height'] > 0)) { // get image height $imgh = $this->getHTMLUnitToUnits($dom[$key]['height'], $this->lasth, 'px'); // check for automatic line break $autolinebreak = false; if (isset($dom[$key]['width']) AND ($dom[$key]['width'] > 0)) { $imgw = $this->getHTMLUnitToUnits($dom[$key]['width'], 1, 'px', false); if (($this->rtl AND (($this->x - $imgw) < ($this->lMargin + $this->cMargin))) OR (!$this->rtl AND (($this->x + $imgw) > ($this->w - $this->rMargin - $this->cMargin)))) { // add automatic line break $autolinebreak = true; $this->Ln('', $cell); // go back to evaluate this line break --$key; } } if (!$autolinebreak) { if (!$this->InFooter) { $pre_y = $this->y; // check for page break if ((!$this->checkPageBreak($imgh)) AND ($this->y < $pre_y)) { // fix for multicolumn mode $startliney = $this->y; } } if ($this->page > $startlinepage) { // fix line splitted over two pages if (isset($this->footerlen[$startlinepage])) { $curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage]; } // line to be moved one page forward $pagebuff = $this->getPageBuffer($startlinepage); $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos)); $tstart = substr($pagebuff, 0, $startlinepos); $tend = substr($this->getPageBuffer($startlinepage), $curpos); // remove line from previous page $this->setPageBuffer($startlinepage, $tstart.''.$tend); $pagebuff = $this->getPageBuffer($this->page); $tstart = substr($pagebuff, 0, $this->cntmrk[$this->page]); $tend = substr($pagebuff, $this->cntmrk[$this->page]); // add line start to current page $yshift = $minstartliney - $this->y; if ($fontaligned) { $yshift += ($curfontsize / $this->k); } $try = sprintf('1 0 0 1 0 %.3F cm', ($yshift * $this->k)); $this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend); // shift the annotations and links if (isset($this->PageAnnots[$this->page])) { $next_pask = count($this->PageAnnots[$this->page]); } else { $next_pask = 0; } if (isset($this->PageAnnots[$startlinepage])) { foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) { if ($pak >= $pask) { $this->PageAnnots[$this->page][] = $pac; unset($this->PageAnnots[$startlinepage][$pak]); $npak = count($this->PageAnnots[$this->page]) - 1; $this->PageAnnots[$this->page][$npak]['y'] -= $yshift; } } } $pask = $next_pask; $startlinepos = $this->cntmrk[$this->page]; $startlinepage = $this->page; $startliney = $this->y; $this->newline = false; } $this->y += ((($curfontsize * $this->cell_height_ratio / $this->k) + $curfontascent - $curfontdescent) / 2) - $imgh; $minstartliney = min($this->y, $minstartliney); $maxbottomliney = ($startliney + ($this->FontSize * $this->cell_height_ratio)); } } elseif (isset($dom[$key]['fontname']) OR isset($dom[$key]['fontstyle']) OR isset($dom[$key]['fontsize']) OR isset($dom[$key]['line-height'])) { // account for different font size $pfontname = $curfontname; $pfontstyle = $curfontstyle; $pfontsize = $curfontsize; $fontname = isset($dom[$key]['fontname']) ? $dom[$key]['fontname'] : $curfontname; $fontstyle = isset($dom[$key]['fontstyle']) ? $dom[$key]['fontstyle'] : $curfontstyle; $fontsize = isset($dom[$key]['fontsize']) ? $dom[$key]['fontsize'] : $curfontsize; $fontascent = $this->getFontAscent($fontname, $fontstyle, $fontsize); $fontdescent = $this->getFontDescent($fontname, $fontstyle, $fontsize); if (($fontname != $curfontname) OR ($fontstyle != $curfontstyle) OR ($fontsize != $curfontsize) OR ($this->cell_height_ratio != $dom[$key]['line-height'])) { if ((!$this->newline) AND ($key < ($maxel - 1)) AND ((is_numeric($fontsize) AND ($fontsize >= 0) AND is_numeric($curfontsize) AND ($curfontsize >= 0) AND ($fontsize != $curfontsize)) OR ($this->cell_height_ratio != $dom[$key]['line-height']))) { if ($this->page > $startlinepage) { // fix lines splitted over two pages if (isset($this->footerlen[$startlinepage])) { $curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage]; } // line to be moved one page forward $pagebuff = $this->getPageBuffer($startlinepage); $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos)); $tstart = substr($pagebuff, 0, $startlinepos); $tend = substr($this->getPageBuffer($startlinepage), $curpos); // remove line start from previous page $this->setPageBuffer($startlinepage, $tstart.''.$tend); $pagebuff = $this->getPageBuffer($this->page); $tstart = substr($pagebuff, 0, $this->cntmrk[$this->page]); $tend = substr($pagebuff, $this->cntmrk[$this->page]); // add line start to current page $yshift = $minstartliney - $this->y; $try = sprintf('1 0 0 1 0 %.3F cm', ($yshift * $this->k)); $this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend); // shift the annotations and links if (isset($this->PageAnnots[$this->page])) { $next_pask = count($this->PageAnnots[$this->page]); } else { $next_pask = 0; } if (isset($this->PageAnnots[$startlinepage])) { foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) { if ($pak >= $pask) { $this->PageAnnots[$this->page][] = $pac; unset($this->PageAnnots[$startlinepage][$pak]); $npak = count($this->PageAnnots[$this->page]) - 1; $this->PageAnnots[$this->page][$npak]['y'] -= $yshift; } } } $pask = $next_pask; $startlinepos = $this->cntmrk[$this->page]; $startlinepage = $this->page; $startliney = $this->y; } if (!isset($dom[$key]['line-height'])) { $dom[$key]['line-height'] = $this->cell_height_ratio; } if (!$dom[$key]['block']) { $this->y += (((($curfontsize * $this->cell_height_ratio ) - ($fontsize * $dom[$key]['line-height'])) / $this->k) + $curfontascent - $fontascent - $curfontdescent + $fontdescent) / 2; if (($dom[$key]['value'] != 'sup') AND ($dom[$key]['value'] != 'sub')) { $minstartliney = min($this->y, $minstartliney); $maxbottomliney = max(($this->y + (($fontsize * $this->cell_height_ratio) / $this->k)), $maxbottomliney); } } $this->cell_height_ratio = $dom[$key]['line-height']; $fontaligned = true; } $this->SetFont($fontname, $fontstyle, $fontsize); $this->lasth = $this->FontSize * $this->cell_height_ratio; $curfontname = $fontname; $curfontstyle = $fontstyle; $curfontsize = $fontsize; $curfontascent = $fontascent; $curfontdescent = $fontdescent; } } // set text rendering mode $textstroke = isset($dom[$key]['stroke']) ? $dom[$key]['stroke'] : $this->textstrokewidth; $textfill = isset($dom[$key]['fill']) ? $dom[$key]['fill'] : (($this->textrendermode % 2) == 0); $textclip = isset($dom[$key]['clip']) ? $dom[$key]['clip'] : ($this->textrendermode > 3); $this->setTextRenderingMode($textstroke, $textfill, $textclip); if (($plalign == 'J') AND $dom[$key]['block']) { $plalign = ''; } // get current position on page buffer $curpos = $this->pagelen[$startlinepage]; if (isset($dom[$key]['bgcolor']) AND ($dom[$key]['bgcolor'] !== false)) { $this->SetFillColorArray($dom[$key]['bgcolor']); $wfill = true; } else { $wfill = $fill | false; } if (isset($dom[$key]['fgcolor']) AND ($dom[$key]['fgcolor'] !== false)) { $this->SetTextColorArray($dom[$key]['fgcolor']); } if (isset($dom[$key]['strokecolor']) AND ($dom[$key]['strokecolor'] !== false)) { $this->SetDrawColorArray($dom[$key]['strokecolor']); } if (isset($dom[$key]['align'])) { $lalign = $dom[$key]['align']; } if ($this->empty_string($lalign)) { $lalign = $align; } } // align lines if ($this->newline AND (strlen($dom[$key]['value']) > 0) AND ($dom[$key]['value'] != 'td') AND ($dom[$key]['value'] != 'th')) { $newline = true; $fontaligned = false; // we are at the beginning of a new line if (isset($startlinex)) { $yshift = $minstartliney - $startliney; if (($yshift > 0) OR ($this->page > $startlinepage)) { $yshift = 0; } $t_x = 0; // the last line must be shifted to be aligned as requested $linew = abs($this->endlinex - $startlinex); $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos); if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) { $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage]; $midpos = min($opentagpos, $this->footerpos[$startlinepage]); } elseif (isset($opentagpos)) { $midpos = $opentagpos; } elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) { $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage]; $midpos = $this->footerpos[$startlinepage]; } else { $midpos = 0; } if ($midpos > 0) { $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos)); $pend = substr($this->getPageBuffer($startlinepage), $midpos); } else { $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos); $pend = ''; } if ((isset($plalign) AND ((($plalign == 'C') OR ($plalign == 'J') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl)))))) { // calculate shifting amount $tw = $w; if (($plalign == 'J') AND $this->isRTLTextDir() AND ($this->num_columns > 1)) { $tw += $this->cMargin; } if ($this->lMargin != $prevlMargin) { $tw += ($prevlMargin - $this->lMargin); } if ($this->rMargin != $prevrMargin) { $tw += ($prevrMargin - $this->rMargin); } $one_space_width = $this->GetStringWidth(chr(32)); $no = 0; // number of spaces on a line contained on a single block if ($this->isRTLTextDir()) { // RTL // remove left space if exist $pos1 = $this->revstrpos($pmid, '[('); if ($pos1 > 0) { $pos1 = intval($pos1); if ($this->isUnicodeFont()) { $pos2 = intval($this->revstrpos($pmid, '[('.chr(0).chr(32))); $spacelen = 2; } else { $pos2 = intval($this->revstrpos($pmid, '[('.chr(32))); $spacelen = 1; } if ($pos1 == $pos2) { $pmid = substr($pmid, 0, ($pos1 + 2)).substr($pmid, ($pos1 + 2 + $spacelen)); if (substr($pmid, $pos1, 4) == '[()]') { $linew -= $one_space_width; } elseif ($pos1 == strpos($pmid, '[(')) { $no = 1; } } } } else { // LTR // remove right space if exist $pos1 = $this->revstrpos($pmid, ')]'); if ($pos1 > 0) { $pos1 = intval($pos1); if ($this->isUnicodeFont()) { $pos2 = intval($this->revstrpos($pmid, chr(0).chr(32).')]')) + 2; $spacelen = 2; } else { $pos2 = intval($this->revstrpos($pmid, chr(32).')]')) + 1; $spacelen = 1; } if ($pos1 == $pos2) { $pmid = substr($pmid, 0, ($pos1 - $spacelen)).substr($pmid, $pos1); $linew -= $one_space_width; } } } $mdiff = ($tw - $linew); if ($plalign == 'C') { if ($this->rtl) { $t_x = -($mdiff / 2); } else { $t_x = ($mdiff / 2); } } elseif ($plalign == 'R') { // right alignment on LTR document $t_x = $mdiff; } elseif ($plalign == 'L') { // left alignment on RTL document $t_x = -$mdiff; } elseif (($plalign == 'J') AND ($plalign == $lalign)) { // Justification if ($this->isRTLTextDir()) { // align text on the left $t_x = -$mdiff; } $ns = 0; // number of spaces $pmidtemp = $pmid; // escape special characters $pmidtemp = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmidtemp); $pmidtemp = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmidtemp); // search spaces if (preg_match_all('/\[\(([^\)]*)\)\]/x', $pmidtemp, $lnstring, PREG_PATTERN_ORDER)) { $spacestr = $this->getSpaceString(); $maxkk = count($lnstring[1]) - 1; for ($kk=0; $kk <= $maxkk; ++$kk) { // restore special characters $lnstring[1][$kk] = str_replace('#!#OP#!#', '(', $lnstring[1][$kk]); $lnstring[1][$kk] = str_replace('#!#CP#!#', ')', $lnstring[1][$kk]); // store number of spaces on the strings $lnstring[2][$kk] = substr_count($lnstring[1][$kk], $spacestr); // count total spaces on line $ns += $lnstring[2][$kk]; $lnstring[3][$kk] = $ns; } if ($ns == 0) { $ns = 1; } // calculate additional space to add to each existing space $spacewidth = ($mdiff / ($ns - $no)) * $this->k; $spacewidthu = -1000 * ($mdiff + (($ns + $no) * $one_space_width)) / $ns / $this->FontSize; $nsmax = $ns; $ns = 0; reset($lnstring); $offset = 0; $strcount = 0; $prev_epsposbeg = 0; $textpos = 0; if ($this->isRTLTextDir()) { $textpos = $this->wPt; } global $spacew; while (preg_match('/([0-9\.\+\-]*)[\s](Td|cm|m|l|c|re)[\s]/x', $pmid, $strpiece, PREG_OFFSET_CAPTURE, $offset) == 1) { // check if we are inside a string section '[( ... )]' $stroffset = strpos($pmid, '[(', $offset); if (($stroffset !== false) AND ($stroffset <= $strpiece[2][1])) { // set offset to the end of string section $offset = strpos($pmid, ')]', $stroffset); while (($offset !== false) AND ($pmid{($offset - 1)} == '\\')) { $offset = strpos($pmid, ')]', ($offset + 1)); } if ($offset === false) { $this->Error('HTML Justification: malformed PDF code.'); } continue; } if ($this->isRTLTextDir()) { $spacew = ($spacewidth * ($nsmax - $ns)); } else { $spacew = ($spacewidth * $ns); } $offset = $strpiece[2][1] + strlen($strpiece[2][0]); $epsposbeg = strpos($pmid, 'q'.$this->epsmarker, $offset); $epsposend = strpos($pmid, $this->epsmarker.'Q', $offset) + strlen($this->epsmarker.'Q'); if ((($epsposbeg > 0) AND ($epsposend > 0) AND ($offset > $epsposbeg) AND ($offset < $epsposend)) OR (($epsposbeg === false) AND ($epsposend > 0) AND ($offset < $epsposend))) { // shift EPS images $trx = sprintf('1 0 0 1 %.3F 0 cm', $spacew); $epsposbeg = strpos($pmid, 'q'.$this->epsmarker, ($prev_epsposbeg - 6)); $pmid_b = substr($pmid, 0, $epsposbeg); $pmid_m = substr($pmid, $epsposbeg, ($epsposend - $epsposbeg)); $pmid_e = substr($pmid, $epsposend); $pmid = $pmid_b."\nq\n".$trx."\n".$pmid_m."\nQ\n".$pmid_e; $offset = $epsposend; continue; } $prev_epsposbeg = $epsposbeg; $currentxpos = 0; // shift blocks of code switch ($strpiece[2][0]) { case 'Td': case 'cm': case 'm': case 'l': { // get current X position preg_match('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $xmatches); $currentxpos = $xmatches[1]; $textpos = $currentxpos; if (($strcount <= $maxkk) AND ($strpiece[2][0] == 'Td')) { $ns = $lnstring[3][$strcount]; if ($this->isRTLTextDir()) { $spacew = ($spacewidth * ($nsmax - $ns)); } ++$strcount; } // justify block $pmid = preg_replace_callback('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', create_function('$matches', 'global $spacew; $newx = sprintf("%.2F",(floatval($matches[1]) + $spacew)); return "".$newx." ".$matches[2]." x*#!#*x".$matches[3].$matches[4];'), $pmid, 1); break; } case 're': { // justify block if (!$this->empty_string($this->lispacer)) { $this->lispacer = ''; continue; } preg_match('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s](re)([\s]*)/x', $pmid, $xmatches); $currentxpos = $xmatches[1]; global $x_diff, $w_diff; $x_diff = 0; $w_diff = 0; if ($this->isRTLTextDir()) { // RTL if ($currentxpos < $textpos) { $x_diff = ($spacewidth * ($nsmax - $lnstring[3][$strcount])); $w_diff = ($spacewidth * $lnstring[2][$strcount]); } else { if ($strcount > 0) { $x_diff = ($spacewidth * ($nsmax - $lnstring[3][($strcount - 1)])); $w_diff = ($spacewidth * $lnstring[2][($strcount - 1)]); } } } else { // LTR if ($currentxpos > $textpos) { if ($strcount > 0) { $x_diff = ($spacewidth * $lnstring[3][($strcount - 1)]); } $w_diff = ($spacewidth * $lnstring[2][$strcount]); } else { if ($strcount > 1) { $x_diff = ($spacewidth * $lnstring[3][($strcount - 2)]); } if ($strcount > 0) { $w_diff = ($spacewidth * $lnstring[2][($strcount - 1)]); } } } $pmid = preg_replace_callback('/('.$xmatches[1].')[\s]('.$xmatches[2].')[\s]('.$xmatches[3].')[\s]('.$strpiece[1][0].')[\s](re)([\s]*)/x', create_function('$matches', 'global $x_diff, $w_diff; $newx = sprintf("%.2F",(floatval($matches[1]) + $x_diff)); $neww = sprintf("%.2F",(floatval($matches[3]) + $w_diff)); return "".$newx." ".$matches[2]." ".$neww." ".$matches[4]." x*#!#*x".$matches[5].$matches[6];'), $pmid, 1); break; } case 'c': { // get current X position preg_match('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s](c)([\s]*)/x', $pmid, $xmatches); $currentxpos = $xmatches[1]; // justify block $pmid = preg_replace_callback('/('.$xmatches[1].')[\s]('.$xmatches[2].')[\s]('.$xmatches[3].')[\s]('.$xmatches[4].')[\s]('.$xmatches[5].')[\s]('.$strpiece[1][0].')[\s](c)([\s]*)/x', create_function('$matches', 'global $spacew; $newx1 = sprintf("%.3F",(floatval($matches[1]) + $spacew)); $newx2 = sprintf("%.3F",(floatval($matches[3]) + $spacew)); $newx3 = sprintf("%.3F",(floatval($matches[5]) + $spacew)); return "".$newx1." ".$matches[2]." ".$newx2." ".$matches[4]." ".$newx3." ".$matches[6]." x*#!#*x".$matches[7].$matches[8];'), $pmid, 1); break; } } // shift the annotations and links if (isset($this->PageAnnots[$this->page])) { $cxpos = ($currentxpos / $this->k); $lmpos = ($this->lMargin + $this->cMargin + $this->feps); foreach ($this->PageAnnots[$this->page] as $pak => $pac) { if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k) >= ($currentxpos - $this->feps)) AND (($pac['x'] * $this->k) <= ($currentxpos + $this->feps))) { if ($cxpos > $lmpos) { $this->PageAnnots[$this->page][$pak]['x'] += ($spacew / $this->k); $this->PageAnnots[$this->page][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k); } else { $this->PageAnnots[$this->page][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k); } break; } } } } // end of while // remove markers $pmid = str_replace('x*#!#*x', '', $pmid); if ($this->isUnicodeFont()) { // multibyte characters $spacew = $spacewidthu; $pmidtemp = $pmid; // escape special characters $pmidtemp = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmidtemp); $pmidtemp = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmidtemp); $pmid = preg_replace_callback("/\[\(([^\)]*)\)\]/x", create_function('$matches', 'global $spacew; $matches[1] = str_replace("#!#OP#!#", "(", $matches[1]); $matches[1] = str_replace("#!#CP#!#", ")", $matches[1]); return "[(".str_replace(chr(0).chr(32), ") ".sprintf("%.3F", $spacew)." (", $matches[1]).")]";'), $pmidtemp); $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\n".$pend); $endlinepos = strlen($pstart."\n".$pmid."\n"); } else { // non-unicode (single-byte characters) $rs = sprintf('%.3F Tw', $spacewidth); $pmid = preg_replace("/\[\(/x", $rs.' [(', $pmid); $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend); $endlinepos = strlen($pstart."\n".$pmid."\nBT 0 Tw ET\n"); } } } // end of J } // end if $startlinex if (($t_x != 0) OR ($yshift < 0)) { // shift the line $trx = sprintf('1 0 0 1 %.3F %.3F cm', ($t_x * $this->k), ($yshift * $this->k)); $this->setPageBuffer($startlinepage, $pstart."\nq\n".$trx."\n".$pmid."\nQ\n".$pend); $endlinepos = strlen($pstart."\nq\n".$trx."\n".$pmid."\nQ\n"); // shift the annotations and links if (isset($this->PageAnnots[$this->page])) { foreach ($this->PageAnnots[$this->page] as $pak => $pac) { if ($pak >= $pask) { $this->PageAnnots[$this->page][$pak]['x'] += $t_x; $this->PageAnnots[$this->page][$pak]['y'] -= $yshift; } } } $this->y -= $yshift; } } $pbrk = $this->checkPageBreak($this->lasth); $this->newline = false; $startlinex = $this->x; $startliney = $this->y; if ($dom[$dom[$key]['parent']]['value'] == 'sup') { $startliney -= ((0.3 * $this->FontSizePt) / $this->k); } elseif ($dom[$dom[$key]['parent']]['value'] == 'sub') { $startliney -= (($this->FontSizePt / 0.7) / $this->k); } else { $minstartliney = $startliney; $maxbottomliney = ($this->y + (($fontsize * $this->cell_height_ratio) / $this->k)); } $startlinepage = $this->page; if (isset($endlinepos) AND (!$pbrk)) { $startlinepos = $endlinepos; } else { if (!$this->InFooter) { if (isset($this->footerlen[$this->page])) { $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page]; } else { $this->footerpos[$this->page] = $this->pagelen[$this->page]; } $startlinepos = $this->footerpos[$this->page]; } else { $startlinepos = $this->pagelen[$this->page]; } } unset($endlinepos); $plalign = $lalign; if (isset($this->PageAnnots[$this->page])) { $pask = count($this->PageAnnots[$this->page]); } else { $pask = 0; } if (!($dom[$key]['tag'] AND !$dom[$key]['opening'] AND ($dom[$key]['value'] == 'table') AND ($this->emptypagemrk[$this->page] == $this->pagelen[$this->page]))) { $this->SetFont($fontname, $fontstyle, $fontsize); if ($wfill) { $this->SetFillColorArray($this->bgcolor); } } } // end newline if (isset($opentagpos)) { unset($opentagpos); } if ($dom[$key]['tag']) { if ($dom[$key]['opening']) { // get text indentation (if any) if (isset($dom[$key]['text-indent']) AND $dom[$key]['block']) { $this->textindent = $dom[$key]['text-indent']; $this->newline = true; } // table if ($dom[$key]['value'] == 'table') { // available page width if ($this->rtl) { $wtmp = $this->x - $this->lMargin; } else { $wtmp = $this->w - $this->rMargin - $this->x; } if (isset($dom[$key]['attribute']['cellspacing'])) { $cellspacing = $this->getHTMLUnitToUnits($dom[$key]['attribute']['cellspacing'], 1, 'px'); } else { $cellspacing = 0; } // table width if (isset($dom[$key]['width'])) { $table_width = $this->getHTMLUnitToUnits($dom[$key]['width'], $wtmp, 'px'); } else { $table_width = $wtmp; } $table_width -= (2 * $cellspacing); if (!$this->inthead) { $this->y += $cellspacing; } if ($this->rtl) { $cellspacingx = -$cellspacing; } else { $cellspacingx = $cellspacing; } // total table width without cellspaces $table_columns_width = ($table_width - ($cellspacing * ($dom[$key]['cols'] - 1))); // minimum column width $table_min_column_width = ($table_columns_width / $dom[$key]['cols']); // array of custom column widths $table_colwidths = array_fill(0, $dom[$key]['cols'], $table_min_column_width); } // table row if ($dom[$key]['value'] == 'tr') { // reset column counter $colid = 0; } // table cell if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) { $trid = $dom[$key]['parent']; $table_el = $dom[$trid]['parent']; if (!isset($dom[$table_el]['cols'])) { $dom[$table_el]['cols'] = $dom[$trid]['cols']; } // store border info $tdborder = 0; if (isset($dom[$key]['border']) AND !empty($dom[$key]['border'])) { $tdborder = $dom[$key]['border']; } $colspan = $dom[$key]['attribute']['colspan']; $oldmargin = $this->cMargin; if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'])) { $currentcmargin = $this->getHTMLUnitToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'], 1, 'px'); } else { $currentcmargin = 0; } $this->cMargin = $currentcmargin; if (isset($dom[$key]['height'])) { // minimum cell height $cellh = $this->getHTMLUnitToUnits($dom[$key]['height'], 0, 'px'); } else { $cellh = 0; } if (isset($dom[$key]['content'])) { $cell_content = $dom[$key]['content']; } else { $cell_content = '&nbsp;'; } $tagtype = $dom[$key]['value']; $parentid = $key; while (($key < $maxel) AND (!(($dom[$key]['tag']) AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == $tagtype) AND ($dom[$key]['parent'] == $parentid)))) { // move $key index forward ++$key; } if (!isset($dom[$trid]['startpage'])) { $dom[$trid]['startpage'] = $this->page; } else { $this->setPage($dom[$trid]['startpage']); } if (!isset($dom[$trid]['startcolumn'])) { $dom[$trid]['startcolumn'] = $this->current_column; } elseif ($this->current_column != $dom[$trid]['startcolumn']) { $tmpx = $this->x; $this->selectColumn($dom[$trid]['startcolumn']); $this->x = $tmpx; } if (!isset($dom[$trid]['starty'])) { $dom[$trid]['starty'] = $this->y; } else { $this->y = $dom[$trid]['starty']; } if (!isset($dom[$trid]['startx'])) { $dom[$trid]['startx'] = $this->x; $this->x += $cellspacingx; } else { $this->x += ($cellspacingx / 2); } if (isset($dom[$parentid]['attribute']['rowspan'])) { $rowspan = intval($dom[$parentid]['attribute']['rowspan']); } else { $rowspan = 1; } // skip row-spanned cells started on the previous rows if (isset($dom[$table_el]['rowspans'])) { $rsk = 0; $rskmax = count($dom[$table_el]['rowspans']); while ($rsk < $rskmax) { $trwsp = $dom[$table_el]['rowspans'][$rsk]; $rsstartx = $trwsp['startx']; $rsendx = $trwsp['endx']; // account for margin changes if ($trwsp['startpage'] < $this->page) { if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$trwsp['startpage']]['orm'])) { $dl = ($this->pagedim[$this->page]['orm'] - $this->pagedim[$trwsp['startpage']]['orm']); $rsstartx -= $dl; $rsendx -= $dl; } elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$trwsp['startpage']]['olm'])) { $dl = ($this->pagedim[$this->page]['olm'] - $this->pagedim[$trwsp['startpage']]['olm']); $rsstartx += $dl; $rsendx += $dl; } } if (($trwsp['rowspan'] > 0) AND ($rsstartx > ($this->x - $cellspacing - $currentcmargin - $this->feps)) AND ($rsstartx < ($this->x + $cellspacing + $currentcmargin + $this->feps)) AND (($trwsp['starty'] < ($this->y - $this->feps)) OR ($trwsp['startpage'] < $this->page) OR ($trwsp['startcolumn'] < $this->current_column))) { // set the starting X position of the current cell $this->x = $rsendx + $cellspacingx; // increment column indicator $colid += $trwsp['colspan']; if (($trwsp['rowspan'] == 1) AND (isset($dom[$trid]['endy'])) AND (isset($dom[$trid]['endpage'])) AND (isset($dom[$trid]['endcolumn'])) AND ($trwsp['endpage'] == $dom[$trid]['endpage']) AND ($trwsp['endcolumn'] == $dom[$trid]['endcolumn'])) { // set ending Y position for row $dom[$table_el]['rowspans'][$rsk]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']); $dom[$trid]['endy'] = $dom[$table_el]['rowspans'][$rsk]['endy']; } $rsk = 0; } else { ++$rsk; } } } if (isset($dom[$parentid]['width'])) { // user specified width $cellw = $this->getHTMLUnitToUnits($dom[$parentid]['width'], $table_columns_width, 'px'); $tmpcw = ($cellw / $colspan); for ($i = 0; $i < $colspan; ++$i) { $table_colwidths[($colid + $i)] = $tmpcw; } } else { // inherit column width $cellw = 0; for ($i = 0; $i < $colspan; ++$i) { $cellw += $table_colwidths[($colid + $i)]; } } $cellw += (($colspan - 1) * $cellspacing); // increment column indicator $colid += $colspan; // add rowspan information to table element if ($rowspan > 1) { $trsid = array_push($dom[$table_el]['rowspans'], array('trid' => $trid, 'rowspan' => $rowspan, 'mrowspan' => $rowspan, 'colspan' => $colspan, 'startpage' => $this->page, 'startcolumn' => $this->current_column, 'startx' => $this->x, 'starty' => $this->y)); } $cellid = array_push($dom[$trid]['cellpos'], array('startx' => $this->x)); if ($rowspan > 1) { $dom[$trid]['cellpos'][($cellid - 1)]['rowspanid'] = ($trsid - 1); } // push background colors if (isset($dom[$parentid]['bgcolor']) AND ($dom[$parentid]['bgcolor'] !== false)) { $dom[$trid]['cellpos'][($cellid - 1)]['bgcolor'] = $dom[$parentid]['bgcolor']; } // store border info if (isset($tdborder) AND !empty($tdborder)) { $dom[$trid]['cellpos'][($cellid - 1)]['border'] = $tdborder; } $prevLastH = $this->lasth; // store some info for multicolumn mode if ($this->rtl) { $this->colxshift['x'] = $this->w - $this->x - $this->rMargin; } else { $this->colxshift['x'] = $this->x - $this->lMargin; } $this->colxshift['s'] = $cellspacing; $this->colxshift['p'] = $currentcmargin; // ****** write the cell content ****** $this->MultiCell($cellw, $cellh, $cell_content, false, $lalign, false, 2, '', '', true, 0, true); // restore some values $this->colxshift = array('x' => 0, 's' => 0, 'p' => 0); $this->lasth = $prevLastH; $this->cMargin = $oldmargin; $dom[$trid]['cellpos'][($cellid - 1)]['endx'] = $this->x; // update the end of row position if ($rowspan <= 1) { if (isset($dom[$trid]['endy'])) { if (($this->page == $dom[$trid]['endpage']) AND ($this->current_column == $dom[$trid]['endcolumn'])) { $dom[$trid]['endy'] = max($this->y, $dom[$trid]['endy']); } elseif (($this->page > $dom[$trid]['endpage']) OR ($this->current_column > $dom[$trid]['endcolumn'])) { $dom[$trid]['endy'] = $this->y; } } else { $dom[$trid]['endy'] = $this->y; } if (isset($dom[$trid]['endpage'])) { $dom[$trid]['endpage'] = max($this->page, $dom[$trid]['endpage']); } else { $dom[$trid]['endpage'] = $this->page; } if (isset($dom[$trid]['endcolumn'])) { $dom[$trid]['endcolumn'] = max($this->current_column, $dom[$trid]['endcolumn']); } else { $dom[$trid]['endcolumn'] = $this->current_column; } } else { // account for row-spanned cells $dom[$table_el]['rowspans'][($trsid - 1)]['endx'] = $this->x; $dom[$table_el]['rowspans'][($trsid - 1)]['endy'] = $this->y; $dom[$table_el]['rowspans'][($trsid - 1)]['endpage'] = $this->page; $dom[$table_el]['rowspans'][($trsid - 1)]['endcolumn'] = $this->current_column; } if (isset($dom[$table_el]['rowspans'])) { // update endy and endpage on rowspanned cells foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) { if ($trwsp['rowspan'] > 0) { if (isset($dom[$trid]['endpage'])) { if (($trwsp['endpage'] == $dom[$trid]['endpage']) AND ($trwsp['endcolumn'] == $dom[$trid]['endcolumn'])) { $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']); } elseif (($trwsp['endpage'] < $dom[$trid]['endpage']) OR ($trwsp['endcolumn'] < $dom[$trid]['endcolumn'])) { $dom[$table_el]['rowspans'][$k]['endy'] = $dom[$trid]['endy']; $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[$trid]['endpage']; $dom[$table_el]['rowspans'][$k]['endcolumn'] = $dom[$trid]['endcolumn']; } else { $dom[$trid]['endy'] = $this->pagedim[$dom[$trid]['endpage']]['hk'] - $this->pagedim[$dom[$trid]['endpage']]['bm']; } } } } } $this->x += ($cellspacingx / 2); } else { // opening tag (or self-closing tag) if (!isset($opentagpos)) { if (!$this->InFooter) { if (isset($this->footerlen[$this->page])) { $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page]; } else { $this->footerpos[$this->page] = $this->pagelen[$this->page]; } $opentagpos = $this->footerpos[$this->page]; } } $this->openHTMLTagHandler($dom, $key, $cell); } } else { // closing tag $prev_numpages = $this->numpages; $old_bordermrk = $this->bordermrk[$this->page]; $this->closeHTMLTagHandler($dom, $key, $cell, $maxbottomliney); if ($this->bordermrk[$this->page] > $old_bordermrk) { $startlinepos += ($this->bordermrk[$this->page] - $old_bordermrk); } if ($prev_numpages > $this->numpages) { $startlinepage = $this->page; } } } elseif (strlen($dom[$key]['value']) > 0) { // print list-item if (!$this->empty_string($this->lispacer) AND ($this->lispacer != '^')) { $this->SetFont($pfontname, $pfontstyle, $pfontsize); $this->lasth = $this->FontSize * $this->cell_height_ratio; $minstartliney = $this->y; $maxbottomliney = ($startliney + ($this->FontSize * $this->cell_height_ratio)); $this->putHtmlListBullet($this->listnum, $this->lispacer, $pfontsize); $this->SetFont($curfontname, $curfontstyle, $curfontsize); $this->lasth = $this->FontSize * $this->cell_height_ratio; if (is_numeric($pfontsize) AND ($pfontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($pfontsize != $curfontsize)) { $pfontascent = $this->getFontAscent($pfontname, $pfontstyle, $pfontsize); $pfontdescent = $this->getFontDescent($pfontname, $pfontstyle, $pfontsize); $this->y += ((($pfontsize - $curfontsize) * $this->cell_height_ratio / $this->k) + $pfontascent - $curfontascent - $pfontdescent + $curfontdescent) / 2; $minstartliney = min($this->y, $minstartliney); $maxbottomliney = max(($this->y + (($pfontsize * $this->cell_height_ratio) / $this->k)), $maxbottomliney); } } // text $this->htmlvspace = 0; if ((!$this->premode) AND $this->isRTLTextDir()) { // reverse spaces order $lsp = ''; // left spaces $rsp = ''; // right spaces if (preg_match('/^('.$this->re_space['p'].'+)/'.$this->re_space['m'], $dom[$key]['value'], $matches)) { $lsp = $matches[1]; } if (preg_match('/('.$this->re_space['p'].'+)$/'.$this->re_space['m'], $dom[$key]['value'], $matches)) { $rsp = $matches[1]; } $dom[$key]['value'] = $rsp.$this->stringTrim($dom[$key]['value']).$lsp; } if ($newline) { if (!$this->premode) { $prelen = strlen($dom[$key]['value']); if ($this->isRTLTextDir()) { // right trim except non-breaking space $dom[$key]['value'] = $this->stringRightTrim($dom[$key]['value']); } else { // left trim except non-breaking space $dom[$key]['value'] = $this->stringLeftTrim($dom[$key]['value']); } $postlen = strlen($dom[$key]['value']); if (($postlen == 0) AND ($prelen > 0)) { $dom[$key]['trimmed_space'] = true; } } $newline = false; $firstblock = true; } else { $firstblock = false; // replace empty multiple spaces string with a single space $dom[$key]['value'] = preg_replace('/^'.$this->re_space['p'].'+$/'.$this->re_space['m'], chr(32), $dom[$key]['value']); } $strrest = ''; if ($this->rtl) { $this->x -= $this->textindent; } else { $this->x += $this->textindent; } if (!isset($dom[$key]['trimmed_space']) OR !$dom[$key]['trimmed_space']) { if (!empty($this->HREF) AND (isset($this->HREF['url']))) { // HTML <a> Link $hrefcolor = ''; if (isset($dom[($dom[$key]['parent'])]['fgcolor']) AND ($dom[($dom[$key]['parent'])]['fgcolor'] !== false)) { $hrefcolor = $dom[($dom[$key]['parent'])]['fgcolor']; } $hrefstyle = -1; if (isset($dom[($dom[$key]['parent'])]['fontstyle']) AND ($dom[($dom[$key]['parent'])]['fontstyle'] !== false)) { $hrefstyle = $dom[($dom[$key]['parent'])]['fontstyle']; } $strrest = $this->addHtmlLink($this->HREF['url'], $dom[$key]['value'], $wfill, true, $hrefcolor, $hrefstyle, true); } else { // check the next text block for continuity $wadj = 0; $nkey = ($key + 1); while (isset($dom[$nkey]) AND $dom[$nkey]['tag'] AND (!$dom[$nkey]['block'])) { ++$nkey; } if (isset($dom[$nkey]) AND (!$dom[$nkey]['block'])) { $nextstr = preg_split('/'.$this->re_space['p'].'+/'.$this->re_space['m'], $dom[$nkey]['value']); $nextstr = $nextstr[0]; if (!$this->empty_string($nextstr)) { // preserve line continuity $wadj = $this->GetStringWidth($nextstr); } } // ****** write only until the end of the line and get the rest ****** $strrest = $this->Write($this->lasth, $dom[$key]['value'], '', $wfill, '', false, 0, true, $firstblock, 0, $wadj); } } $this->textindent = 0; if (strlen($strrest) > 0) { // store the remaining string on the previous $key position $this->newline = true; if ($strrest == $dom[$key]['value']) { // used to avoid infinite loop ++$loop; } else { $loop = 0; } $dom[$key]['value'] = $strrest; if ($cell) { if ($this->rtl) { $this->x -= $this->cMargin; } else { $this->x += $this->cMargin; } } if ($loop < 3) { --$key; } } else { $loop = 0; } } ++$key; if (isset($dom[$key]['tag']) AND $dom[$key]['tag'] AND (!isset($dom[$key]['opening']) OR !$dom[$key]['opening']) AND isset($dom[($dom[$key]['parent'])]['attribute']['nobr']) AND ($dom[($dom[$key]['parent'])]['attribute']['nobr'] == 'true')) { if ( (!$undo) AND (($this->start_transaction_page == ($this->numpages - 1)) OR ($this->y < $this->start_transaction_y))) { // restore previous object $this->rollbackTransaction(true); // restore previous values foreach ($this_method_vars as $vkey => $vval) { $$vkey = $vval; } // add a page (or trig AcceptPageBreak() for multicolumn mode) $pre_y = $this->y; if ((!$this->checkPageBreak($this->PageBreakTrigger + 1)) AND ($this->y < $pre_y)) { $startliney = $this->y; } $undo = true; // avoid infinite loop } else { $undo = false; } } } // end for each $key // align the last line if (isset($startlinex)) { $yshift = $minstartliney - $startliney; if (($yshift > 0) OR ($this->page > $startlinepage)) { $yshift = 0; } $t_x = 0; // the last line must be shifted to be aligned as requested $linew = abs($this->endlinex - $startlinex); $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos); if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) { $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage]; $midpos = min($opentagpos, $this->footerpos[$startlinepage]); } elseif (isset($opentagpos)) { $midpos = $opentagpos; } elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) { $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage]; $midpos = $this->footerpos[$startlinepage]; } else { $midpos = 0; } if ($midpos > 0) { $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos)); $pend = substr($this->getPageBuffer($startlinepage), $midpos); } else { $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos); $pend = ''; } if ((isset($plalign) AND ((($plalign == 'C') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl)))))) { // calculate shifting amount $tw = $w; if ($this->lMargin != $prevlMargin) { $tw += ($prevlMargin - $this->lMargin); } if ($this->rMargin != $prevrMargin) { $tw += ($prevrMargin - $this->rMargin); } $one_space_width = $this->GetStringWidth(chr(32)); $no = 0; // number of spaces on a line contained on a single block if ($this->isRTLTextDir()) { // RTL // remove left space if exist $pos1 = $this->revstrpos($pmid, '[('); if ($pos1 > 0) { $pos1 = intval($pos1); if ($this->isUnicodeFont()) { $pos2 = intval($this->revstrpos($pmid, '[('.chr(0).chr(32))); $spacelen = 2; } else { $pos2 = intval($this->revstrpos($pmid, '[('.chr(32))); $spacelen = 1; } if ($pos1 == $pos2) { $pmid = substr($pmid, 0, ($pos1 + 2)).substr($pmid, ($pos1 + 2 + $spacelen)); if (substr($pmid, $pos1, 4) == '[()]') { $linew -= $one_space_width; } elseif ($pos1 == strpos($pmid, '[(')) { $no = 1; } } } } else { // LTR // remove right space if exist $pos1 = $this->revstrpos($pmid, ')]'); if ($pos1 > 0) { $pos1 = intval($pos1); if ($this->isUnicodeFont()) { $pos2 = intval($this->revstrpos($pmid, chr(0).chr(32).')]')) + 2; $spacelen = 2; } else { $pos2 = intval($this->revstrpos($pmid, chr(32).')]')) + 1; $spacelen = 1; } if ($pos1 == $pos2) { $pmid = substr($pmid, 0, ($pos1 - $spacelen)).substr($pmid, $pos1); $linew -= $one_space_width; } } } $mdiff = ($tw - $linew); if ($plalign == 'C') { if ($this->rtl) { $t_x = -($mdiff / 2); } else { $t_x = ($mdiff / 2); } } elseif ($plalign == 'R') { // right alignment on LTR document $t_x = $mdiff; } elseif ($plalign == 'L') { // left alignment on RTL document $t_x = -$mdiff; } } // end if startlinex if (($t_x != 0) OR ($yshift < 0)) { // shift the line $trx = sprintf('1 0 0 1 %.3F %.3F cm', ($t_x * $this->k), ($yshift * $this->k)); $this->setPageBuffer($startlinepage, $pstart."\nq\n".$trx."\n".$pmid."\nQ\n".$pend); $endlinepos = strlen($pstart."\nq\n".$trx."\n".$pmid."\nQ\n"); // shift the annotations and links if (isset($this->PageAnnots[$this->page])) { foreach ($this->PageAnnots[$this->page] as $pak => $pac) { if ($pak >= $pask) { $this->PageAnnots[$this->page][$pak]['x'] += $t_x; $this->PageAnnots[$this->page][$pak]['y'] -= $yshift; } } } $this->y -= $yshift; } } // restore previous values $this->setGraphicVars($gvars); if ($this->num_columns > 1) { $this->selectColumn(); } elseif ($this->page > $prevPage) { $this->lMargin = $this->pagedim[$this->page]['olm']; $this->rMargin = $this->pagedim[$this->page]['orm']; } // restore previous list state $this->cell_height_ratio = $prev_cell_height_ratio; $this->listnum = $prev_listnum; $this->listordered = $prev_listordered; $this->listcount = $prev_listcount; $this->lispacer = $prev_lispacer; if ($ln AND (!($cell AND ($dom[$key-1]['value'] == 'table')))) { $this->Ln($this->lasth); if ($this->y < $maxbottomliney) { $this->y = $maxbottomliney; } } unset($dom); } /** * Process opening tags. * @param array $dom html dom array * @param int $key current element id * @param boolean $cell if true add the default cMargin space to each new line (default false). * @access protected */ protected function openHTMLTagHandler(&$dom, $key, $cell) { $tag = $dom[$key]; $parent = $dom[($dom[$key]['parent'])]; $firsttag = ($key == 1); // check for text direction attribute if (isset($tag['attribute']['dir'])) { $this->setTempRTL($tag['attribute']['dir']); } else { $this->tmprtl = false; } if ($tag['block']) { $hbz = 0; // distance from y to line bottom $hb = 0; // vertical space between block tags // calculate vertical space for block tags if (isset($this->tagvspaces[$tag['value']][0]['h']) AND ($this->tagvspaces[$tag['value']][0]['h'] >= 0)) { $cur_h = $this->tagvspaces[$tag['value']][0]['h']; } elseif (isset($tag['fontsize'])) { $cur_h = ($tag['fontsize'] / $this->k) * $this->cell_height_ratio; } else { $cur_h = $this->FontSize * $this->cell_height_ratio; } if (isset($this->tagvspaces[$tag['value']][0]['n'])) { $n = $this->tagvspaces[$tag['value']][0]['n']; } elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) { $n = 0.6; } else { $n = 1; } $hb = ($n * $cur_h); if (($this->htmlvspace <= 0) AND ($n > 0)) { if (isset($parent['fontsize'])) { $hbz = (($parent['fontsize'] / $this->k) * $this->cell_height_ratio); } else { $hbz = $this->FontSize * $this->cell_height_ratio; } } } // Opening tag switch($tag['value']) { case 'table': { $cp = 0; $cs = 0; $dom[$key]['rowspans'] = array(); if (!isset($dom[$key]['attribute']['nested']) OR ($dom[$key]['attribute']['nested'] != 'true')) { // set table header if (!$this->empty_string($dom[$key]['thead'])) { // set table header $this->thead = $dom[$key]['thead']; if (!isset($this->theadMargins) OR (empty($this->theadMargins))) { $this->theadMargins = array(); $this->theadMargins['cmargin'] = $this->cMargin; $this->theadMargins['lmargin'] = $this->lMargin; $this->theadMargins['rmargin'] = $this->rMargin; $this->theadMargins['page'] = $this->page; } } } // store current margins and page $dom[$key]['oldcmargin'] = $this->cMargin; if (isset($tag['attribute']['cellpadding'])) { $this->cMargin = $this->getHTMLUnitToUnits($tag['attribute']['cellpadding'], 1, 'px'); } if (isset($tag['attribute']['cellspacing'])) { $cs = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px'); } $prev_y = $this->y; if ($this->checkPageBreak(((2 * $cp) + (2 * $cs) + $this->lasth), '', false) OR ($this->y < $prev_y)) { $this->inthead = true; // add a page (or trig AcceptPageBreak() for multicolumn mode) $this->checkPageBreak($this->PageBreakTrigger + 1); } break; } case 'tr': { // array of columns positions $dom[$key]['cellpos'] = array(); break; } case 'hr': { if ((isset($tag['height'])) AND ($tag['height'] != '')) { $hrHeight = $this->getHTMLUnitToUnits($tag['height'], 1, 'px'); } else { $hrHeight = $this->GetLineWidth(); } $this->addHTMLVertSpace($hbz, ($hrHeight / 2), $cell, $firsttag); $x = $this->GetX(); $y = $this->GetY(); $wtmp = $this->w - $this->lMargin - $this->rMargin; if ($cell) { $wtmp -= 2 * $this->cMargin; } if ((isset($tag['width'])) AND ($tag['width'] != '')) { $hrWidth = $this->getHTMLUnitToUnits($tag['width'], $wtmp, 'px'); } else { $hrWidth = $wtmp; } $prevlinewidth = $this->GetLineWidth(); $this->SetLineWidth($hrHeight); $this->Line($x, $y, $x + $hrWidth, $y); $this->SetLineWidth($prevlinewidth); $this->addHTMLVertSpace(($hrHeight / 2), 0, $cell, !isset($dom[($key + 1)])); break; } case 'a': { if (array_key_exists('href', $tag['attribute'])) { $this->HREF['url'] = $tag['attribute']['href']; } break; } case 'img': { if (isset($tag['attribute']['src'])) { // replace relative path with real server path if (($tag['attribute']['src'][0] == '/') AND ($_SERVER['DOCUMENT_ROOT'] != '/')) { $findroot = strpos($tag['attribute']['src'], $_SERVER['DOCUMENT_ROOT']); if (($findroot === false) OR ($findroot > 1)) { $tag['attribute']['src'] = $_SERVER['DOCUMENT_ROOT'].$tag['attribute']['src']; } } $tag['attribute']['src'] = urldecode($tag['attribute']['src']); $type = $this->getImageFileType($tag['attribute']['src']); $testscrtype = @parse_url($tag['attribute']['src']); if (!isset($testscrtype['query']) OR empty($testscrtype['query'])) { // convert URL to server path $tag['attribute']['src'] = str_replace(K_PATH_URL, K_PATH_MAIN, $tag['attribute']['src']); } if (!isset($tag['width'])) { $tag['width'] = 0; } if (!isset($tag['height'])) { $tag['height'] = 0; } //if (!isset($tag['attribute']['align'])) { // the only alignment supported is "bottom" // further development is required for other modes. $tag['attribute']['align'] = 'bottom'; //} switch($tag['attribute']['align']) { case 'top': { $align = 'T'; break; } case 'middle': { $align = 'M'; break; } case 'bottom': { $align = 'B'; break; } default: { $align = 'B'; break; } } $prevy = $this->y; $xpos = $this->x; // eliminate marker spaces if (isset($dom[($key - 1)])) { if (($dom[($key - 1)]['value'] == ' ') OR (isset($dom[($key - 1)]['trimmed_space']))) { $xpos -= $this->GetStringWidth(chr(32)); } elseif ($this->rtl AND $dom[($key - 1)]['value'] == ' ') { $xpos += (2 * $this->GetStringWidth(chr(32))); } } $imglink = ''; if (isset($this->HREF['url']) AND !$this->empty_string($this->HREF['url'])) { $imglink = $this->HREF['url']; if ($imglink{0} == '#') { // convert url to internal link $page = intval(substr($imglink, 1)); $imglink = $this->AddLink(); $this->SetLink($imglink, 0, $page); } } $border = 0; if (isset($tag['border']) AND !empty($tag['border'])) { // currently only support 1 (frame) or a combination of 'LTRB' $border = $tag['border']; } $iw = ''; if (isset($tag['width'])) { $iw = $this->getHTMLUnitToUnits($tag['width'], 1, 'px', false); } $ih = ''; if (isset($tag['height'])) { $ih = $this->getHTMLUnitToUnits($tag['height'], 1, 'px', false); } if (($type == 'eps') OR ($type == 'ai')) { $this->ImageEps($tag['attribute']['src'], $xpos, $this->y, $iw, $ih, $imglink, true, $align, '', $border, true); } elseif ($type == 'svg') { $this->ImageSVG($tag['attribute']['src'], $xpos, $this->y, $iw, $ih, $imglink, $align, '', $border, true); } else { $this->Image($tag['attribute']['src'], $xpos, $this->y, $iw, $ih, '', $imglink, $align, false, 300, '', false, false, $border, false, false, true); } switch($align) { case 'T': { $this->y = $prevy; break; } case 'M': { $this->y = (($this->img_rb_y + $prevy - ($tag['fontsize'] / $this->k)) / 2) ; break; } case 'B': { $this->y = $this->img_rb_y - ($tag['fontsize'] / $this->k); break; } } } break; } case 'dl': { ++$this->listnum; if ($this->listnum == 1) { $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag); } else { $this->addHTMLVertSpace(0, 0, $cell, $firsttag); } break; } case 'dt': { $this->addHTMLVertSpace($hbz, 0, $cell, $firsttag); break; } case 'dd': { if ($this->rtl) { $this->rMargin += $this->listindent; } else { $this->lMargin += $this->listindent; } ++$this->listindentlevel; $this->addHTMLVertSpace($hbz, 0, $cell, $firsttag); break; } case 'ul': case 'ol': { ++$this->listnum; if ($tag['value'] == 'ol') { $this->listordered[$this->listnum] = true; } else { $this->listordered[$this->listnum] = false; } if (isset($tag['attribute']['start'])) { $this->listcount[$this->listnum] = intval($tag['attribute']['start']) - 1; } else { $this->listcount[$this->listnum] = 0; } if ($this->rtl) { $this->rMargin += $this->listindent; $this->x -= $this->listindent; } else { $this->lMargin += $this->listindent; $this->x += $this->listindent; } ++$this->listindentlevel; if ($this->listnum == 1) { $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag); } else { $this->addHTMLVertSpace(0, 0, $cell, $firsttag); } break; } case 'li': { $this->addHTMLVertSpace($hbz, 0, $cell, $firsttag); if ($this->listordered[$this->listnum]) { // ordered item if (isset($parent['attribute']['type']) AND !$this->empty_string($parent['attribute']['type'])) { $this->lispacer = $parent['attribute']['type']; } elseif (isset($parent['listtype']) AND !$this->empty_string($parent['listtype'])) { $this->lispacer = $parent['listtype']; } elseif (isset($this->lisymbol) AND !$this->empty_string($this->lisymbol)) { $this->lispacer = $this->lisymbol; } else { $this->lispacer = '#'; } ++$this->listcount[$this->listnum]; if (isset($tag['attribute']['value'])) { $this->listcount[$this->listnum] = intval($tag['attribute']['value']); } } else { // unordered item if (isset($parent['attribute']['type']) AND !$this->empty_string($parent['attribute']['type'])) { $this->lispacer = $parent['attribute']['type']; } elseif (isset($parent['listtype']) AND !$this->empty_string($parent['listtype'])) { $this->lispacer = $parent['listtype']; } elseif (isset($this->lisymbol) AND !$this->empty_string($this->lisymbol)) { $this->lispacer = $this->lisymbol; } else { $this->lispacer = '!'; } } break; } case 'blockquote': { if ($this->rtl) { $this->rMargin += $this->listindent; } else { $this->lMargin += $this->listindent; } ++$this->listindentlevel; $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag); break; } case 'br': { $this->addHTMLVertSpace($hbz, 0, $cell, $firsttag); break; } case 'div': { $this->addHTMLVertSpace($hbz, 0, $cell, $firsttag); break; } case 'p': { $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag); break; } case 'pre': { $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag); $this->premode = true; break; } case 'sup': { $this->SetXY($this->GetX(), $this->GetY() - ((0.7 * $this->FontSizePt) / $this->k)); break; } case 'sub': { $this->SetXY($this->GetX(), $this->GetY() + ((0.3 * $this->FontSizePt) / $this->k)); break; } case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': { $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag); break; } // Form fields (since 4.8.000 - 2009-09-07) case 'form': { if (isset($tag['attribute']['action'])) { $this->form_action = $tag['attribute']['action']; } else { $this->form_action = K_PATH_URL.$_SERVER['SCRIPT_NAME']; } if (isset($tag['attribute']['enctype'])) { $this->form_enctype = $tag['attribute']['enctype']; } else { $this->form_enctype = 'application/x-www-form-urlencoded'; } if (isset($tag['attribute']['method'])) { $this->form_mode = $tag['attribute']['method']; } else { $this->form_mode = 'post'; } break; } case 'input': { if (isset($tag['attribute']['name']) AND !$this->empty_string($tag['attribute']['name'])) { $name = $tag['attribute']['name']; } else { break; } $prop = array(); $opt = array(); if (isset($tag['attribute']['readonly']) AND !$this->empty_string($tag['attribute']['readonly'])) { $prop['readonly'] = true; } if (isset($tag['attribute']['value']) AND !$this->empty_string($tag['attribute']['value'])) { $value = $tag['attribute']['value']; } if (isset($tag['attribute']['maxlength']) AND !$this->empty_string($tag['attribute']['maxlength'])) { $opt['maxlen'] = intval($tag['attribute']['value']); } $h = $this->FontSize * $this->cell_height_ratio; if (isset($tag['attribute']['size']) AND !$this->empty_string($tag['attribute']['size'])) { $w = intval($tag['attribute']['size']) * $this->GetStringWidth(chr(32)) * 2; } else { $w = $h; } if (isset($tag['attribute']['checked']) AND (($tag['attribute']['checked'] == 'checked') OR ($tag['attribute']['checked'] == 'true'))) { $checked = true; } else { $checked = false; } switch ($tag['attribute']['type']) { case 'text': { if (isset($value)) { $opt['v'] = $value; } $this->TextField($name, $w, $h, $prop, $opt, '', '', false); break; } case 'password': { if (isset($value)) { $opt['v'] = $value; } $prop['password'] = 'true'; $this->TextField($name, $w, $h, $prop, $opt, '', '', false); break; } case 'checkbox': { $this->CheckBox($name, $w, $checked, $prop, $opt, $value, '', '', false); break; } case 'radio': { $this->RadioButton($name, $w, $prop, $opt, $value, $checked, '', '', false); break; } case 'submit': { $w = $this->GetStringWidth($value) * 1.5; $h *= 1.6; $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255)); $action = array(); $action['S'] = 'SubmitForm'; $action['F'] = $this->form_action; if ($this->form_enctype != 'FDF') { $action['Flags'] = array('ExportFormat'); } if ($this->form_mode == 'get') { $action['Flags'] = array('GetMethod'); } $this->Button($name, $w, $h, $value, $action, $prop, $opt, '', '', false); break; } case 'reset': { $w = $this->GetStringWidth($value) * 1.5; $h *= 1.6; $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255)); $this->Button($name, $w, $h, $value, array('S'=>'ResetForm'), $prop, $opt, '', '', false); break; } case 'file': { $prop['fileSelect'] = 'true'; $this->TextField($name, $w, $h, $prop, $opt, '', '', false); if (!isset($value)) { $value = '*'; } $w = $this->GetStringWidth($value) * 2; $h *= 1.2; $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255)); $jsaction = 'var f=this.getField(\''.$name.'\'); f.browseForFileToSubmit();'; $this->Button('FB_'.$name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false); break; } case 'hidden': { if (isset($value)) { $opt['v'] = $value; } $opt['f'] = array('invisible', 'hidden'); $this->TextField($name, 0, 0, $prop, $opt, '', '', false); break; } case 'image': { // THIS TYPE MUST BE FIXED if (isset($tag['attribute']['src']) AND !$this->empty_string($tag['attribute']['src'])) { $img = $tag['attribute']['src']; } else { break; } $value = 'img'; //$opt['mk'] = array('i'=>$img, 'tp'=>1, 'if'=>array('sw'=>'A', 's'=>'A', 'fb'=>false)); if (isset($tag['attribute']['onclick']) AND !empty($tag['attribute']['onclick'])) { $jsaction = $tag['attribute']['onclick']; } else { $jsaction = ''; } $this->Button($name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false); break; } case 'button': { $w = $this->GetStringWidth($value) * 1.5; $h *= 1.6; $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255)); if (isset($tag['attribute']['onclick']) AND !empty($tag['attribute']['onclick'])) { $jsaction = $tag['attribute']['onclick']; } else { $jsaction = ''; } $this->Button($name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false); break; } } break; } case 'textarea': { $prop = array(); $opt = array(); if (isset($tag['attribute']['readonly']) AND !$this->empty_string($tag['attribute']['readonly'])) { $prop['readonly'] = true; } if (isset($tag['attribute']['name']) AND !$this->empty_string($tag['attribute']['name'])) { $name = $tag['attribute']['name']; } else { break; } if (isset($tag['attribute']['value']) AND !$this->empty_string($tag['attribute']['value'])) { $opt['v'] = $tag['attribute']['value']; } if (isset($tag['attribute']['cols']) AND !$this->empty_string($tag['attribute']['cols'])) { $w = intval($tag['attribute']['cols']) * $this->GetStringWidth(chr(32)) * 2; } else { $w = 40; } if (isset($tag['attribute']['rows']) AND !$this->empty_string($tag['attribute']['rows'])) { $h = intval($tag['attribute']['rows']) * $this->FontSize * $this->cell_height_ratio; } else { $h = 10; } $prop['multiline'] = 'true'; $this->TextField($name, $w, $h, $prop, $opt, '', '', false); break; } case 'select': { $h = $this->FontSize * $this->cell_height_ratio; if (isset($tag['attribute']['size']) AND !$this->empty_string($tag['attribute']['size'])) { $h *= ($tag['attribute']['size'] + 1); } $prop = array(); $opt = array(); if (isset($tag['attribute']['name']) AND !$this->empty_string($tag['attribute']['name'])) { $name = $tag['attribute']['name']; } else { break; } $w = 0; if (isset($tag['attribute']['opt']) AND !$this->empty_string($tag['attribute']['opt'])) { $options = explode('#!NwL!#', $tag['attribute']['opt']); $values = array(); foreach ($options as $val) { if (strpos($val, '#!TaB!#') !== false) { $opts = explode('#!TaB!#', $val); $values[] = $opts; $w = max($w, $this->GetStringWidth($opts[1])); } else { $values[] = $val; $w = max($w, $this->GetStringWidth($val)); } } } else { break; } $w *= 2; if (isset($tag['attribute']['multiple']) AND ($tag['attribute']['multiple']='multiple')) { $prop['multipleSelection'] = 'true'; $this->ListBox($name, $w, $h, $values, $prop, $opt, '', '', false); } else { $this->ComboBox($name, $w, $h, $values, $prop, $opt, '', '', false); } break; } case 'tcpdf': { if (defined('K_TCPDF_CALLS_IN_HTML') AND (K_TCPDF_CALLS_IN_HTML === true)) { // Special tag used to call TCPDF methods if (isset($tag['attribute']['method'])) { $tcpdf_method = $tag['attribute']['method']; if (method_exists($this, $tcpdf_method)) { if (isset($tag['attribute']['params']) AND (!empty($tag['attribute']['params']))) { $params = unserialize(urldecode($tag['attribute']['params'])); call_user_func_array(array($this, $tcpdf_method), $params); } else { $this->$tcpdf_method(); } $this->newline = true; } } } break; } default: { break; } } // define tags that support borders and background colors $bordertags = array('blockquote','br','dd','dl','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','pre','ul','tcpdf','table'); if (in_array($tag['value'], $bordertags)) { // set border $dom[$key]['borderposition'] = $this->getBorderStartPosition(); } if ($dom[$key]['self'] AND isset($dom[$key]['attribute']['pagebreakafter'])) { $pba = $dom[$key]['attribute']['pagebreakafter']; // check for pagebreak if (($pba == 'true') OR ($pba == 'left') OR ($pba == 'right')) { // add a page (or trig AcceptPageBreak() for multicolumn mode) $this->checkPageBreak($this->PageBreakTrigger + 1); } if ((($pba == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0)))) OR (($pba == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) { // add a page (or trig AcceptPageBreak() for multicolumn mode) $this->checkPageBreak($this->PageBreakTrigger + 1); } } } /** * Process closing tags. * @param array $dom html dom array * @param int $key current element id * @param boolean $cell if true add the default cMargin space to each new line (default false). * @param int $maxbottomliney maximum y value of current line * @access protected */ protected function closeHTMLTagHandler(&$dom, $key, $cell, $maxbottomliney=0) { $tag = $dom[$key]; $parent = $dom[($dom[$key]['parent'])]; $lasttag = ((!isset($dom[($key + 1)])) OR ((!isset($dom[($key + 2)])) AND ($dom[($key + 1)]['value'] == 'marker'))); $in_table_head = false; // maximum x position (used to draw borders) if ($this->rtl) { $xmax = $this->w; } else { $xmax = 0; } if ($tag['block']) { $hbz = 0; // distance from y to line bottom $hb = 0; // vertical space between block tags // calculate vertical space for block tags if (isset($this->tagvspaces[$tag['value']][1]['h']) AND ($this->tagvspaces[$tag['value']][1]['h'] >= 0)) { $pre_h = $this->tagvspaces[$tag['value']][1]['h']; } elseif (isset($parent['fontsize'])) { $pre_h = (($parent['fontsize'] / $this->k) * $this->cell_height_ratio); } else { $pre_h = $this->FontSize * $this->cell_height_ratio; } if (isset($this->tagvspaces[$tag['value']][1]['n'])) { $n = $this->tagvspaces[$tag['value']][1]['n']; } elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) { $n = 0.6; } else { $n = 1; } $hb = ($n * $pre_h); if ($this->y < $maxbottomliney) { $hbz = ($maxbottomliney - $this->y); } } // Closing tag switch($tag['value']) { case 'tr': { $table_el = $dom[($dom[$key]['parent'])]['parent']; if (!isset($parent['endy'])) { $dom[($dom[$key]['parent'])]['endy'] = $this->y; $parent['endy'] = $this->y; } if (!isset($parent['endpage'])) { $dom[($dom[$key]['parent'])]['endpage'] = $this->page; $parent['endpage'] = $this->page; } if (!isset($parent['endcolumn'])) { $dom[($dom[$key]['parent'])]['endcolumn'] = $this->current_column; $parent['endcolumn'] = $this->current_column; } // update row-spanned cells if (isset($dom[$table_el]['rowspans'])) { foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) { $dom[$table_el]['rowspans'][$k]['rowspan'] -= 1; if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) { if (($dom[$table_el]['rowspans'][$k]['endpage'] == $parent['endpage']) AND ($dom[$table_el]['rowspans'][$k]['endcolumn'] == $parent['endcolumn'])) { $dom[($dom[$key]['parent'])]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $parent['endy']); } elseif (($dom[$table_el]['rowspans'][$k]['endpage'] > $parent['endpage']) OR ($dom[$table_el]['rowspans'][$k]['endcolumn'] > $parent['endcolumn'])) { $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy']; $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage']; $dom[($dom[$key]['parent'])]['endcolumn'] = $dom[$table_el]['rowspans'][$k]['endcolumn']; } } } // report new endy and endpage to the rowspanned cells foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) { if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) { $dom[$table_el]['rowspans'][$k]['endpage'] = max($dom[$table_el]['rowspans'][$k]['endpage'], $dom[($dom[$key]['parent'])]['endpage']); $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage']; $dom[$table_el]['rowspans'][$k]['endcolumn'] = max($dom[$table_el]['rowspans'][$k]['endcolumn'], $dom[($dom[$key]['parent'])]['endcolumn']); $dom[($dom[$key]['parent'])]['endcolumn'] = $dom[$table_el]['rowspans'][$k]['endcolumn']; $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $dom[($dom[$key]['parent'])]['endy']); $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy']; } } // update remaining rowspanned cells foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) { if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) { $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[($dom[$key]['parent'])]['endpage']; $dom[$table_el]['rowspans'][$k]['endcolumn'] = $dom[($dom[$key]['parent'])]['endcolumn']; $dom[$table_el]['rowspans'][$k]['endy'] = $dom[($dom[$key]['parent'])]['endy']; } } } $this->setPage($dom[($dom[$key]['parent'])]['endpage']); if ($this->num_columns > 1) { $this->selectColumn($dom[($dom[$key]['parent'])]['endcolumn']); } $this->y = $dom[($dom[$key]['parent'])]['endy']; if (isset($dom[$table_el]['attribute']['cellspacing'])) { $cellspacing = $this->getHTMLUnitToUnits($dom[$table_el]['attribute']['cellspacing'], 1, 'px'); $this->y += $cellspacing; } $this->Ln(0, $cell); if ($this->current_column == $parent['startcolumn']) { $this->x = $parent['startx']; } // account for booklet mode if ($this->page > $parent['startpage']) { if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$parent['startpage']]['orm'])) { $this->x -= ($this->pagedim[$this->page]['orm'] - $this->pagedim[$parent['startpage']]['orm']); } elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$parent['startpage']]['olm'])) { $this->x += ($this->pagedim[$this->page]['olm'] - $this->pagedim[$parent['startpage']]['olm']); } } break; } case 'tablehead': // closing tag used for the thead part $in_table_head = true; $this->inthead = false; case 'table': { $table_el = $parent; // set default border if (isset($table_el['attribute']['border']) AND ($table_el['attribute']['border'] > 0)) { // set default border $border = array('LTRB' => array('width' => $this->getCSSBorderWidth($table_el['attribute']['border']), 'cap'=>'square', 'join'=>'miter', 'dash'=> 0, 'color'=>array(0,0,0))); } else { $border = 0; } $default_border = $border; if (isset($table_el['attribute']['cellspacing'])) { $cellspacing = $this->getHTMLUnitToUnits($table_el['attribute']['cellspacing'], 1, 'px'); } else { $cellspacing = 0; } // fix bottom line alignment of last line before page break foreach ($dom[($dom[$key]['parent'])]['trids'] as $j => $trkey) { // update row-spanned cells if (isset($dom[($dom[$key]['parent'])]['rowspans'])) { foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) { if ($trwsp['trid'] == $trkey) { $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] -= 1; } if (isset($prevtrkey) AND ($trwsp['trid'] == $prevtrkey) AND ($trwsp['mrowspan'] >= 0)) { $dom[($dom[$key]['parent'])]['rowspans'][$k]['trid'] = $trkey; } } } if (isset($prevtrkey) AND ($dom[$trkey]['startpage'] > $dom[$prevtrkey]['endpage'])) { $pgendy = $this->pagedim[$dom[$prevtrkey]['endpage']]['hk'] - $this->pagedim[$dom[$prevtrkey]['endpage']]['bm']; $dom[$prevtrkey]['endy'] = $pgendy; // update row-spanned cells if (isset($dom[($dom[$key]['parent'])]['rowspans'])) { foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) { if (($trwsp['trid'] == $trkey) AND ($trwsp['mrowspan'] > 1) AND ($trwsp['endpage'] == $dom[$prevtrkey]['endpage'])) { $dom[($dom[$key]['parent'])]['rowspans'][$k]['endy'] = $pgendy; $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] = -1; } } } } $prevtrkey = $trkey; $table_el = $dom[($dom[$key]['parent'])]; } // for each row unset($xmax); foreach ($table_el['trids'] as $j => $trkey) { $parent = $dom[$trkey]; if (!isset($xmax)) { $xmax = $parent['cellpos'][(count($parent['cellpos']) - 1)]['endx']; } // for each cell on the row foreach ($parent['cellpos'] as $k => $cellpos) { if (isset($cellpos['rowspanid']) AND ($cellpos['rowspanid'] >= 0)) { $cellpos['startx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['startx']; $cellpos['endx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['endx']; $endy = $table_el['rowspans'][($cellpos['rowspanid'])]['endy']; $startpage = $table_el['rowspans'][($cellpos['rowspanid'])]['startpage']; $endpage = $table_el['rowspans'][($cellpos['rowspanid'])]['endpage']; $startcolumn = $table_el['rowspans'][($cellpos['rowspanid'])]['startcolumn']; $endcolumn = $table_el['rowspans'][($cellpos['rowspanid'])]['endcolumn']; } else { $endy = $parent['endy']; $startpage = $parent['startpage']; $endpage = $parent['endpage']; $startcolumn = $parent['startcolumn']; $endcolumn = $parent['endcolumn']; } if ($this->num_columns == 0) { $this->num_columns = 1; } if (isset($cellpos['border'])) { $border = $cellpos['border']; } if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) { $this->SetFillColorArray($cellpos['bgcolor']); $fill = true; } else { $fill = false; } $x = $cellpos['startx']; $y = $parent['starty']; $starty = $y; $w = abs($cellpos['endx'] - $cellpos['startx']); // get border modes $border_start = $this->getBorderMode($border, $position='start'); $border_end = $this->getBorderMode($border, $position='end'); $border_middle = $this->getBorderMode($border, $position='middle'); // design borders around HTML cells. for ($page = $startpage; $page <= $endpage; ++$page) { // for each page $ccode = ''; $this->setPage($page); if ($this->num_columns < 2) { // single-column mode $this->x = $x; $this->y = $this->tMargin; } // account for margin changes if ($page > $startpage) { if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) { $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']); } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) { $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']); } } if ($startpage == $endpage) { // single page $deltacol = 0; $deltath = 0; for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column $this->selectColumn($column); if ($startcolumn == $endcolumn) { // single column $cborder = $border; $h = $endy - $parent['starty']; $this->y = $y; $this->x = $x; } elseif ($column == $startcolumn) { // first column $cborder = $border_start; $this->y = $starty; $this->x = $x; $h = $this->h - $this->y - $this->bMargin; if ($this->rtl) { $deltacol = $this->x + $this->rMargin - $this->w; } else { $deltacol = $this->x - $this->lMargin; } } elseif ($column == $endcolumn) { // end column $cborder = $border_end; if (isset($this->columns[$column]['th']['\''.$page.'\''])) { $this->y = $this->columns[$column]['th']['\''.$page.'\'']; } $this->x += $deltacol; $h = $endy - $this->y; } else { // middle column $cborder = $border_middle; if (isset($this->columns[$column]['th']['\''.$page.'\''])) { $this->y = $this->columns[$column]['th']['\''.$page.'\'']; } $this->x += $deltacol; $h = $this->h - $this->y - $this->bMargin; } $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n"; } // end for each column } elseif ($page == $startpage) { // first page $deltacol = 0; $deltath = 0; for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column $this->selectColumn($column); if ($column == $startcolumn) { // first column $cborder = $border_start; $this->y = $starty; $this->x = $x; $h = $this->h - $this->y - $this->bMargin; if ($this->rtl) { $deltacol = $this->x + $this->rMargin - $this->w; } else { $deltacol = $this->x - $this->lMargin; } } else { // middle column $cborder = $border_middle; if (isset($this->columns[$column]['th']['\''.$page.'\''])) { $this->y = $this->columns[$column]['th']['\''.$page.'\'']; } $this->x += $deltacol; $h = $this->h - $this->y - $this->bMargin; } $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n"; } // end for each column } elseif ($page == $endpage) { // last page $deltacol = 0; $deltath = 0; for ($column = 0; $column <= $endcolumn; ++$column) { // for each column $this->selectColumn($column); if ($column == $endcolumn) { // end column $cborder = $border_end; if (isset($this->columns[$column]['th']['\''.$page.'\''])) { $this->y = $this->columns[$column]['th']['\''.$page.'\'']; } $this->x += $deltacol; $h = $endy - $this->y; } else { // middle column $cborder = $border_middle; if (isset($this->columns[$column]['th']['\''.$page.'\''])) { $this->y = $this->columns[$column]['th']['\''.$page.'\'']; } $this->x += $deltacol; $h = $this->h - $this->y - $this->bMargin; } $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n"; } // end for each column } else { // middle page $deltacol = 0; $deltath = 0; for ($column = 0; $column < $this->num_columns; ++$column) { // for each column $this->selectColumn($column); $cborder = $border_middle; if (isset($this->columns[$column]['th']['\''.$page.'\''])) { $this->y = $this->columns[$column]['th']['\''.$page.'\'']; } $this->x += $deltacol; $h = $this->h - $this->y - $this->bMargin; $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n"; } // end for each column } if ($cborder OR $fill) { // draw border and fill if (end($this->transfmrk[$this->page]) !== false) { $pagemarkkey = key($this->transfmrk[$this->page]); $pagemark = &$this->transfmrk[$this->page][$pagemarkkey]; } elseif ($this->InFooter) { $pagemark = &$this->footerpos[$this->page]; } else { $pagemark = &$this->intmrk[$this->page]; } $pagebuff = $this->getPageBuffer($this->page); $pstart = substr($pagebuff, 0, $pagemark); $pend = substr($pagebuff, $pagemark); $this->setPageBuffer($this->page, $pstart.$ccode.$pend); $pagemark += strlen($ccode); } } // end for each page // restore default border $border = $default_border; } // end for each cell on the row if (isset($table_el['attribute']['cellspacing'])) { $cellspacing = $this->getHTMLUnitToUnits($table_el['attribute']['cellspacing'], 1, 'px'); $this->y += $cellspacing; } $this->Ln(0, $cell); $this->x = $parent['startx']; if ($endpage > $startpage) { if (($this->rtl) AND ($this->pagedim[$endpage]['orm'] != $this->pagedim[$startpage]['orm'])) { $this->x += ($this->pagedim[$endpage]['orm'] - $this->pagedim[$startpage]['orm']); } elseif ((!$this->rtl) AND ($this->pagedim[$endpage]['olm'] != $this->pagedim[$startpage]['olm'])) { $this->x += ($this->pagedim[$endpage]['olm'] - $this->pagedim[$startpage]['olm']); } } } if (!$in_table_head) { // we are not inside a thead section $this->cMargin = $table_el['oldcmargin']; $this->lasth = $this->FontSize * $this->cell_height_ratio; if (($this->page == ($this->numpages - 1)) AND ($this->pageopen[$this->numpages]) AND ($this->emptypagemrk[$this->numpages] == $this->pagelen[$this->numpages])) { // remove last blank page $this->deletePage($this->numpages); } if (isset($this->theadMargins['top'])) { // restore top margin $this->tMargin = $this->theadMargins['top']; $this->pagedim[$this->page]['tm'] = $this->tMargin; } if (!isset($table_el['attribute']['nested']) OR ($table_el['attribute']['nested'] != 'true')) { // reset main table header $this->thead = ''; $this->theadMargins = array(); } } $parent = $table_el; break; } case 'a': { $this->HREF = ''; break; } case 'sup': { $this->SetXY($this->GetX(), $this->GetY() + ((0.7 * $parent['fontsize']) / $this->k)); break; } case 'sub': { $this->SetXY($this->GetX(), $this->GetY() - ((0.3 * $parent['fontsize'])/$this->k)); break; } case 'div': { $this->addHTMLVertSpace($hbz, 0, $cell, false, $lasttag); break; } case 'blockquote': { if ($this->rtl) { $this->rMargin -= $this->listindent; } else { $this->lMargin -= $this->listindent; } --$this->listindentlevel; $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag); break; } case 'p': { $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag); break; } case 'pre': { $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag); $this->premode = false; break; } case 'dl': { --$this->listnum; if ($this->listnum <= 0) { $this->listnum = 0; $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag); } else { $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag); } $this->lasth = $this->FontSize * $this->cell_height_ratio; break; } case 'dt': { $this->lispacer = ''; $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag); break; } case 'dd': { $this->lispacer = ''; if ($this->rtl) { $this->rMargin -= $this->listindent; } else { $this->lMargin -= $this->listindent; } --$this->listindentlevel; $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag); break; } case 'ul': case 'ol': { --$this->listnum; $this->lispacer = ''; if ($this->rtl) { $this->rMargin -= $this->listindent; } else { $this->lMargin -= $this->listindent; } --$this->listindentlevel; if ($this->listnum <= 0) { $this->listnum = 0; $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag); } else { $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag); } $this->lasth = $this->FontSize * $this->cell_height_ratio; break; } case 'li': { $this->lispacer = ''; $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag); break; } case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': { $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag); break; } // Form fields (since 4.8.000 - 2009-09-07) case 'form': { $this->form_action = ''; $this->form_enctype = 'application/x-www-form-urlencoded'; break; } default : { break; } } // draw border and background (if any) $this->drawHTMLTagBorder($parent, $xmax); if (isset($dom[($dom[$key]['parent'])]['attribute']['pagebreakafter'])) { $pba = $dom[($dom[$key]['parent'])]['attribute']['pagebreakafter']; // check for pagebreak if (($pba == 'true') OR ($pba == 'left') OR ($pba == 'right')) { // add a page (or trig AcceptPageBreak() for multicolumn mode) $this->checkPageBreak($this->PageBreakTrigger + 1); } if ((($pba == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0)))) OR (($pba == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) { // add a page (or trig AcceptPageBreak() for multicolumn mode) $this->checkPageBreak($this->PageBreakTrigger + 1); } } $this->tmprtl = false; } /** * Add vertical spaces if needed. * @param string $hbz Distance between current y and line bottom. * @param string $hb The height of the break. * @param boolean $cell if true add the default cMargin space to each new line (default false). * @param boolean $firsttag set to true when the tag is the first. * @param boolean $lasttag set to true when the tag is the last. * @access protected */ protected function addHTMLVertSpace($hbz=0, $hb=0, $cell=false, $firsttag=false, $lasttag=false) { if ($firsttag) { $this->Ln(0, $cell); $this->htmlvspace = 0; return; } if ($lasttag) { $this->Ln($hbz, $cell); $this->htmlvspace = 0; return; } if ($hb < $this->htmlvspace) { $hd = 0; } else { $hd = $hb - $this->htmlvspace; $this->htmlvspace = $hb; } $this->Ln(($hbz + $hd), $cell); } /** * Return the starting coordinates to draw an html border * @return array containing top-left border coordinates * @access protected * @since 5.7.000 (2010-08-03) */ protected function getBorderStartPosition() { if ($this->rtl) { $xmax = $this->lMargin; } else { $xmax = $this->w - $this->rMargin; } return array('page' => $this->page, 'column' => $this->current_column, 'x' => $this->x, 'y' => $this->y, 'xmax' => $xmax); } /** * Draw an HTML block border and fill * @param array $tag array of tag properties. * @param int $xmax end X coordinate for border. * @access protected * @since 5.7.000 (2010-08-03) */ protected function drawHTMLTagBorder($tag, $xmax) { if (!isset($tag['borderposition'])) { // nothing to draw return; } $prev_x = $this->x; $prev_y = $this->y; $prev_lasth = $this->lasth; $border = 0; $fill = false; $this->lasth = 0; if (isset($tag['border']) AND !empty($tag['border'])) { // get border style $border = $tag['border']; if (!$this->empty_string($this->thead) AND (!$this->inthead)) { // border for table header $border = $this->getBorderMode($border, $position='middle'); } } if (isset($tag['bgcolor']) AND ($tag['bgcolor'] !== false)) { // get background color $old_bgcolor = $this->bgcolor; $this->SetFillColorArray($tag['bgcolor']); $fill = true; } if (!$border AND !$fill) { // nothing to draw return; } if (isset($tag['attribute']['cellspacing'])) { $cellspacing = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px'); } else { $cellspacing = 0; } if (($tag['value'] != 'table') AND (is_array($border)) AND (!empty($border))) { // draw the border externally respect the sqare edge. $border['mode'] = 'ext'; } if ($this->rtl) { if ($xmax >= $tag['borderposition']['x']) { $xmax = $tag['borderposition']['xmax']; } $w = ($tag['borderposition']['x'] - $xmax); } else { if ($xmax <= $tag['borderposition']['x']) { $xmax = $tag['borderposition']['xmax']; } $w = ($xmax - $tag['borderposition']['x']); } if ($w <= 0) { return; } $w += $cellspacing; $startpage = $tag['borderposition']['page']; $startcolumn = $tag['borderposition']['column']; $x = $tag['borderposition']['x']; $y = $tag['borderposition']['y']; $endpage = $this->page; $starty = $tag['borderposition']['y'] - $cellspacing; $currentY = $this->y; $this->x = $x; // get latest column $endcolumn = $this->current_column; if ($this->num_columns == 0) { $this->num_columns = 1; } // get border modes $border_start = $this->getBorderMode($border, $position='start'); $border_end = $this->getBorderMode($border, $position='end'); $border_middle = $this->getBorderMode($border, $position='middle'); // design borders around HTML cells. for ($page = $startpage; $page <= $endpage; ++$page) { // for each page $ccode = ''; $this->setPage($page); if ($this->num_columns < 2) { // single-column mode $this->x = $x; $this->y = $this->tMargin; } // account for margin changes if ($page > $startpage) { if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) { $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']); } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) { $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']); } } if ($startpage == $endpage) { // single page for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column $this->selectColumn($column); if ($startcolumn == $endcolumn) { // single column $cborder = $border; $h = ($currentY - $y) + $cellspacing; $this->y = $starty; } elseif ($column == $startcolumn) { // first column $cborder = $border_start; $this->y = $starty; $h = $this->h - $this->y - $this->bMargin; } elseif ($column == $endcolumn) { // end column $cborder = $border_end; $h = $currentY - $this->y; } else { // middle column $cborder = $border_middle; $h = $this->h - $this->y - $this->bMargin; } $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n"; } // end for each column } elseif ($page == $startpage) { // first page for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column $this->selectColumn($column); if ($column == $startcolumn) { // first column $cborder = $border_start; $this->y = $starty; $h = $this->h - $this->y - $this->bMargin; } else { // middle column $cborder = $border_middle; $h = $this->h - $this->y - $this->bMargin; } $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n"; } // end for each column } elseif ($page == $endpage) { // last page for ($column = 0; $column <= $endcolumn; ++$column) { // for each column $this->selectColumn($column); if ($column == $endcolumn) { // end column $cborder = $border_end; $h = $currentY - $this->y; } else { // middle column $cborder = $border_middle; $h = $this->h - $this->y - $this->bMargin; } $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n"; } // end for each column } else { // middle page for ($column = 0; $column < $this->num_columns; ++$column) { // for each column $this->selectColumn($column); $cborder = $border_middle; $h = $this->h - $this->y - $this->bMargin; $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n"; } // end for each column } if ($cborder OR $fill) { // draw border and fill if (end($this->transfmrk[$this->page]) !== false) { $pagemarkkey = key($this->transfmrk[$this->page]); $pagemark = &$this->transfmrk[$this->page][$pagemarkkey]; } elseif ($this->InFooter) { $pagemark = &$this->footerpos[$this->page]; } else { $pagemark = &$this->intmrk[$this->page]; } $pagebuff = $this->getPageBuffer($this->page); $pstart = substr($pagebuff, 0, $this->bordermrk[$this->page]); $pend = substr($pagebuff, $this->bordermrk[$this->page]); $this->setPageBuffer($this->page, $pstart.$ccode.$pend); $offsetlen = strlen($ccode); $this->bordermrk[$this->page] += $offsetlen; $this->cntmrk[$this->page] += $offsetlen; $pagemark += $offsetlen; } } // end for each page if (isset($old_bgcolor)) { // restore background color $this->SetFillColorArray($old_bgcolor); } // restore pointer position $this->x = $prev_x; $this->y = $prev_y; $this->lasth = $prev_lasth; } /** * Set the default bullet to be used as LI bullet symbol * @param string $symbol character or string to be used (legal values are: '' = automatic, '!' = auto bullet, '#' = auto numbering, 'disc', 'disc', 'circle', 'square', '1', 'decimal', 'decimal-leading-zero', 'i', 'lower-roman', 'I', 'upper-roman', 'a', 'lower-alpha', 'lower-latin', 'A', 'upper-alpha', 'upper-latin', 'lower-greek') * @access public * @since 4.0.028 (2008-09-26) */ public function setLIsymbol($symbol='!') { $symbol = strtolower($symbol); switch ($symbol) { case '!' : case '#' : case 'disc' : case 'circle' : case 'square' : case '1': case 'decimal': case 'decimal-leading-zero': case 'i': case 'lower-roman': case 'I': case 'upper-roman': case 'a': case 'lower-alpha': case 'lower-latin': case 'A': case 'upper-alpha': case 'upper-latin': case 'lower-greek': { $this->lisymbol = $symbol; break; } default : { $this->lisymbol = ''; } } } /** * Set the booklet mode for double-sided pages. * @param boolean $booklet true set the booklet mode on, false otherwise. * @param float $inner Inner page margin. * @param float $outer Outer page margin. * @access public * @since 4.2.000 (2008-10-29) */ public function SetBooklet($booklet=true, $inner=-1, $outer=-1) { $this->booklet = $booklet; if ($inner >= 0) { $this->lMargin = $inner; } if ($outer >= 0) { $this->rMargin = $outer; } } /** * Swap the left and right margins. * @param boolean $reverse if true swap left and right margins. * @access protected * @since 4.2.000 (2008-10-29) */ protected function swapMargins($reverse=true) { if ($reverse) { // swap left and right margins $mtemp = $this->original_lMargin; $this->original_lMargin = $this->original_rMargin; $this->original_rMargin = $mtemp; $deltam = $this->original_lMargin - $this->original_rMargin; $this->lMargin += $deltam; $this->rMargin -= $deltam; } } /** * Set the vertical spaces for HTML tags. * The array must have the following structure (example): * $tagvs = array('h1' => array(0 => array('h' => '', 'n' => 2), 1 => array('h' => 1.3, 'n' => 1))); * The first array level contains the tag names, * the second level contains 0 for opening tags or 1 for closing tags, * the third level contains the vertical space unit (h) and the number spaces to add (n). * If the h parameter is not specified, default values are used. * @param array $tagvs array of tags and relative vertical spaces. * @access public * @since 4.2.001 (2008-10-30) */ public function setHtmlVSpace($tagvs) { $this->tagvspaces = $tagvs; } /** * Set custom width for list indentation. * @param float $width width of the indentation. Use negative value to disable it. * @access public * @since 4.2.007 (2008-11-12) */ public function setListIndentWidth($width) { return $this->customlistindent = floatval($width); } /** * Set the top/bottom cell sides to be open or closed when the cell cross the page. * @param boolean $isopen if true keeps the top/bottom border open for the cell sides that cross the page. * @access public * @since 4.2.010 (2008-11-14) */ public function setOpenCell($isopen) { $this->opencell = $isopen; } /** * Set the color and font style for HTML links. * @param array $color RGB array of colors * @param string $fontstyle additional font styles to add * @access public * @since 4.4.003 (2008-12-09) */ public function setHtmlLinksStyle($color=array(0,0,255), $fontstyle='U') { $this->htmlLinkColorArray = $color; $this->htmlLinkFontStyle = $fontstyle; } /** * Convert HTML string containing value and unit of measure to user's units or points. * @param string $htmlval string containing values and unit * @param string $refsize reference value in points * @param string $defaultunit default unit (can be one of the following: %, em, ex, px, in, mm, pc, pt). * @param boolean $point if true returns points, otherwise returns value in user's units * @return float value in user's unit or point if $points=true * @access public * @since 4.4.004 (2008-12-10) */ public function getHTMLUnitToUnits($htmlval, $refsize=1, $defaultunit='px', $points=false) { $supportedunits = array('%', 'em', 'ex', 'px', 'in', 'cm', 'mm', 'pc', 'pt'); $retval = 0; $value = 0; $unit = 'px'; $k = $this->k; if ($points) { $k = 1; } if (in_array($defaultunit, $supportedunits)) { $unit = $defaultunit; } if (is_numeric($htmlval)) { $value = floatval($htmlval); } elseif (preg_match('/([0-9\.\-\+]+)/', $htmlval, $mnum)) { $value = floatval($mnum[1]); if (preg_match('/([a-z%]+)/', $htmlval, $munit)) { if (in_array($munit[1], $supportedunits)) { $unit = $munit[1]; } } } switch ($unit) { // percentage case '%': { $retval = (($value * $refsize) / 100); break; } // relative-size case 'em': { $retval = ($value * $refsize); break; } // height of lower case 'x' (about half the font-size) case 'ex': { $retval = $value * ($refsize / 2); break; } // absolute-size case 'in': { $retval = ($value * $this->dpi) / $k; break; } // centimeters case 'cm': { $retval = ($value / 2.54 * $this->dpi) / $k; break; } // millimeters case 'mm': { $retval = ($value / 25.4 * $this->dpi) / $k; break; } // one pica is 12 points case 'pc': { $retval = ($value * 12) / $k; break; } // points case 'pt': { $retval = $value / $k; break; } // pixels case 'px': { $retval = $this->pixelsToUnits($value); break; } } return $retval; } /** * Returns the Roman representation of an integer number * @param int number to convert * @return string roman representation of the specified number * @access public * @since 4.4.004 (2008-12-10) */ public function intToRoman($number) { $roman = ''; while ($number >= 1000) { $roman .= 'M'; $number -= 1000; } while ($number >= 900) { $roman .= 'CM'; $number -= 900; } while ($number >= 500) { $roman .= 'D'; $number -= 500; } while ($number >= 400) { $roman .= 'CD'; $number -= 400; } while ($number >= 100) { $roman .= 'C'; $number -= 100; } while ($number >= 90) { $roman .= 'XC'; $number -= 90; } while ($number >= 50) { $roman .= 'L'; $number -= 50; } while ($number >= 40) { $roman .= 'XL'; $number -= 40; } while ($number >= 10) { $roman .= 'X'; $number -= 10; } while ($number >= 9) { $roman .= 'IX'; $number -= 9; } while ($number >= 5) { $roman .= 'V'; $number -= 5; } while ($number >= 4) { $roman .= 'IV'; $number -= 4; } while ($number >= 1) { $roman .= 'I'; --$number; } return $roman; } /** * Output an HTML list bullet or ordered item symbol * @param int $listdepth list nesting level * @param string $listtype type of list * @param float $size current font size * @access protected * @since 4.4.004 (2008-12-10) */ protected function putHtmlListBullet($listdepth, $listtype='', $size=10) { $size /= $this->k; $fill = ''; $color = $this->fgcolor; $width = 0; $textitem = ''; $tmpx = $this->x; $lspace = $this->GetStringWidth(' '); if ($listtype == '^') { // special symbol used for avoid justification of rect bullet $this->lispacer = ''; return; } elseif ($listtype == '!') { // set default list type for unordered list $deftypes = array('disc', 'circle', 'square'); $listtype = $deftypes[($listdepth - 1) % 3]; } elseif ($listtype == '#') { // set default list type for ordered list $listtype = 'decimal'; } switch ($listtype) { // unordered types case 'none': { break; } case 'disc': { $fill = 'F'; } case 'circle': { $fill .= 'D'; $r = $size / 6; $lspace += (2 * $r); if ($this->rtl) { $this->x += $lspace; } else { $this->x -= $lspace; } $this->Circle(($this->x + $r), ($this->y + ($this->lasth / 2)), $r, 0, 360, $fill, array('color'=>$color), $color, 8); break; } case 'square': { $l = $size / 3; $lspace += $l; if ($this->rtl) {; $this->x += $lspace; } else { $this->x -= $lspace; } $this->Rect($this->x, ($this->y + (($this->lasth - $l)/ 2)), $l, $l, 'F', array(), $color); break; } // ordered types // $this->listcount[$this->listnum]; // $textitem case '1': case 'decimal': { $textitem = $this->listcount[$this->listnum]; break; } case 'decimal-leading-zero': { $textitem = sprintf('%02d', $this->listcount[$this->listnum]); break; } case 'i': case 'lower-roman': { $textitem = strtolower($this->intToRoman($this->listcount[$this->listnum])); break; } case 'I': case 'upper-roman': { $textitem = $this->intToRoman($this->listcount[$this->listnum]); break; } case 'a': case 'lower-alpha': case 'lower-latin': { $textitem = chr(97 + $this->listcount[$this->listnum] - 1); break; } case 'A': case 'upper-alpha': case 'upper-latin': { $textitem = chr(65 + $this->listcount[$this->listnum] - 1); break; } case 'lower-greek': { $textitem = $this->unichr(945 + $this->listcount[$this->listnum] - 1); break; } /* // Types to be implemented (special handling) case 'hebrew': { break; } case 'armenian': { break; } case 'georgian': { break; } case 'cjk-ideographic': { break; } case 'hiragana': { break; } case 'katakana': { break; } case 'hiragana-iroha': { break; } case 'katakana-iroha': { break; } */ default: { $textitem = $this->listcount[$this->listnum]; } } if (!$this->empty_string($textitem)) { // print ordered item if ($this->rtl) { $textitem = '.'.$textitem; } else { $textitem = $textitem.'.'; } $lspace += $this->GetStringWidth($textitem); if ($this->rtl) { $this->x += $lspace; } else { $this->x -= $lspace; } $this->Write($this->lasth, $textitem, '', false, '', false, 0, false); } $this->x = $tmpx; $this->lispacer = '^'; } /** * Returns current graphic variables as array. * @return array of graphic variables * @access protected * @since 4.2.010 (2008-11-14) */ protected function getGraphicVars() { $grapvars = array( 'FontFamily' => $this->FontFamily, 'FontStyle' => $this->FontStyle, 'FontSizePt' => $this->FontSizePt, 'rMargin' => $this->rMargin, 'lMargin' => $this->lMargin, 'cMargin' => $this->cMargin, 'LineWidth' => $this->LineWidth, 'linestyleWidth' => $this->linestyleWidth, 'linestyleCap' => $this->linestyleCap, 'linestyleJoin' => $this->linestyleJoin, 'linestyleDash' => $this->linestyleDash, 'textrendermode' => $this->textrendermode, 'textstrokewidth' => $this->textstrokewidth, 'DrawColor' => $this->DrawColor, 'FillColor' => $this->FillColor, 'TextColor' => $this->TextColor, 'ColorFlag' => $this->ColorFlag, 'bgcolor' => $this->bgcolor, 'fgcolor' => $this->fgcolor, 'htmlvspace' => $this->htmlvspace, 'listindent' => $this->listindent, 'listindentlevel' => $this->listindentlevel, 'listnum' => $this->listnum, 'listordered' => $this->listordered, 'listcount' => $this->listcount, 'lispacer' => $this->lispacer, 'cell_height_ratio' => $this->cell_height_ratio, // extended 'lasth' => $this->lasth, 'tMargin' => $this->tMargin, 'bMargin' => $this->bMargin, 'AutoPageBreak' => $this->AutoPageBreak, 'PageBreakTrigger' => $this->PageBreakTrigger, 'x' => $this->x, 'y' => $this->y, 'w' => $this->w, 'h' => $this->h, 'wPt' => $this->wPt, 'hPt' => $this->hPt, 'fwPt' => $this->fwPt, 'fhPt' => $this->fhPt, 'page' => $this->page, 'current_column' => $this->current_column, 'num_columns' => $this->num_columns ); return $grapvars; } /** * Set graphic variables. * @param array $gvars array of graphic variablesto restore * @param boolean $extended if true restore extended graphic variables * @access protected * @since 4.2.010 (2008-11-14) */ protected function setGraphicVars($gvars, $extended=false) { $this->FontFamily = $gvars['FontFamily']; $this->FontStyle = $gvars['FontStyle']; $this->FontSizePt = $gvars['FontSizePt']; $this->rMargin = $gvars['rMargin']; $this->lMargin = $gvars['lMargin']; $this->cMargin = $gvars['cMargin']; $this->LineWidth = $gvars['LineWidth']; $this->linestyleWidth = $gvars['linestyleWidth']; $this->linestyleCap = $gvars['linestyleCap']; $this->linestyleJoin = $gvars['linestyleJoin']; $this->linestyleDash = $gvars['linestyleDash']; $this->textrendermode = $gvars['textrendermode']; $this->textstrokewidth = $gvars['textstrokewidth']; $this->DrawColor = $gvars['DrawColor']; $this->FillColor = $gvars['FillColor']; $this->TextColor = $gvars['TextColor']; $this->ColorFlag = $gvars['ColorFlag']; $this->bgcolor = $gvars['bgcolor']; $this->fgcolor = $gvars['fgcolor']; $this->htmlvspace = $gvars['htmlvspace']; $this->listindent = $gvars['listindent']; $this->listindentlevel = $gvars['listindentlevel']; $this->listnum = $gvars['listnum']; $this->listordered = $gvars['listordered']; $this->listcount = $gvars['listcount']; $this->lispacer = $gvars['lispacer']; $this->cell_height_ratio = $gvars['cell_height_ratio']; if ($extended) { // restore extended values $this->lasth = $gvars['lasth']; $this->tMargin = $gvars['tMargin']; $this->bMargin = $gvars['bMargin']; $this->AutoPageBreak = $gvars['AutoPageBreak']; $this->PageBreakTrigger = $gvars['PageBreakTrigger']; $this->x = $gvars['x']; $this->y = $gvars['y']; $this->w = $gvars['w']; $this->h = $gvars['h']; $this->wPt = $gvars['wPt']; $this->hPt = $gvars['hPt']; $this->fwPt = $gvars['fwPt']; $this->fhPt = $gvars['fhPt']; $this->page = $gvars['page']; $this->current_column = $gvars['current_column']; $this->num_columns = $gvars['num_columns']; } $this->_out(''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor.''); if (!$this->empty_string($this->FontFamily)) { $this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt); } } /** * Returns a temporary filename for caching object on filesystem. * @param string $prefix prefix to add to filename * return string filename. * @access protected * @since 4.5.000 (2008-12-31) */ protected function getObjFilename($name) { return tempnam(K_PATH_CACHE, $name.'_'); } /** * Writes data to a temporary file on filesystem. * @param string $file file name * @param mixed $data data to write on file * @param boolean $append if true append data, false replace. * @access protected * @since 4.5.000 (2008-12-31) */ protected function writeDiskCache($filename, $data, $append=false) { if ($append) { $fmode = 'ab+'; } else { $fmode = 'wb+'; } $f = @fopen($filename, $fmode); if (!$f) { $this->Error('Unable to write cache file: '.$filename); } else { fwrite($f, $data); fclose($f); } // update file length (needed for transactions) if (!isset($this->cache_file_length['_'.$filename])) { $this->cache_file_length['_'.$filename] = strlen($data); } else { $this->cache_file_length['_'.$filename] += strlen($data); } } /** * Read data from a temporary file on filesystem. * @param string $file file name * @return mixed retrieved data * @access protected * @since 4.5.000 (2008-12-31) */ protected function readDiskCache($filename) { return file_get_contents($filename); } /** * Set buffer content (always append data). * @param string $data data * @access protected * @since 4.5.000 (2009-01-02) */ protected function setBuffer($data) { $this->bufferlen += strlen($data); if ($this->diskcache) { if (!isset($this->buffer) OR $this->empty_string($this->buffer)) { $this->buffer = $this->getObjFilename('buffer'); } $this->writeDiskCache($this->buffer, $data, true); } else { $this->buffer .= $data; } } /** * Replace the buffer content * @param string $data data * @access protected * @since 5.5.000 (2010-06-22) */ protected function replaceBuffer($data) { $this->bufferlen = strlen($data); if ($this->diskcache) { if (!isset($this->buffer) OR $this->empty_string($this->buffer)) { $this->buffer = $this->getObjFilename('buffer'); } $this->writeDiskCache($this->buffer, $data, false); } else { $this->buffer = $data; } } /** * Get buffer content. * @return string buffer content * @access protected * @since 4.5.000 (2009-01-02) */ protected function getBuffer() { if ($this->diskcache) { return $this->readDiskCache($this->buffer); } else { return $this->buffer; } } /** * Set page buffer content. * @param int $page page number * @param string $data page data * @param boolean $append if true append data, false replace. * @access protected * @since 4.5.000 (2008-12-31) */ protected function setPageBuffer($page, $data, $append=false) { if ($this->diskcache) { if (!isset($this->pages[$page])) { $this->pages[$page] = $this->getObjFilename('page'.$page); } $this->writeDiskCache($this->pages[$page], $data, $append); } else { if ($append) { $this->pages[$page] .= $data; } else { $this->pages[$page] = $data; } } if ($append AND isset($this->pagelen[$page])) { $this->pagelen[$page] += strlen($data); } else { $this->pagelen[$page] = strlen($data); } } /** * Get page buffer content. * @param int $page page number * @return string page buffer content or false in case of error * @access protected * @since 4.5.000 (2008-12-31) */ protected function getPageBuffer($page) { if ($this->diskcache) { return $this->readDiskCache($this->pages[$page]); } elseif (isset($this->pages[$page])) { return $this->pages[$page]; } return false; } /** * Set image buffer content. * @param string $image image key * @param array $data image data * @access protected * @since 4.5.000 (2008-12-31) */ protected function setImageBuffer($image, $data) { if ($this->diskcache) { if (!isset($this->images[$image])) { $this->images[$image] = $this->getObjFilename('image'.$image); } $this->writeDiskCache($this->images[$image], serialize($data)); } else { $this->images[$image] = $data; } if (!in_array($image, $this->imagekeys)) { $this->imagekeys[] = $image; ++$this->numimages; } } /** * Set image buffer content for a specified sub-key. * @param string $image image key * @param string $key image sub-key * @param array $data image data * @access protected * @since 4.5.000 (2008-12-31) */ protected function setImageSubBuffer($image, $key, $data) { if (!isset($this->images[$image])) { $this->setImageBuffer($image, array()); } if ($this->diskcache) { $tmpimg = $this->getImageBuffer($image); $tmpimg[$key] = $data; $this->writeDiskCache($this->images[$image], serialize($tmpimg)); } else { $this->images[$image][$key] = $data; } } /** * Get image buffer content. * @param string $image image key * @return string image buffer content or false in case of error * @access protected * @since 4.5.000 (2008-12-31) */ protected function getImageBuffer($image) { if ($this->diskcache AND isset($this->images[$image])) { return unserialize($this->readDiskCache($this->images[$image])); } elseif (isset($this->images[$image])) { return $this->images[$image]; } return false; } /** * Set font buffer content. * @param string $font font key * @param array $data font data * @access protected * @since 4.5.000 (2009-01-02) */ protected function setFontBuffer($font, $data) { if ($this->diskcache) { if (!isset($this->fonts[$font])) { $this->fonts[$font] = $this->getObjFilename('font'); } $this->writeDiskCache($this->fonts[$font], serialize($data)); } else { $this->fonts[$font] = $data; } if (!in_array($font, $this->fontkeys)) { $this->fontkeys[] = $font; // store object ID for current font ++$this->n; $this->font_obj_ids[$font] = $this->n; $this->setFontSubBuffer($font, 'n', $this->n); } } /** * Set font buffer content. * @param string $font font key * @param string $key font sub-key * @param array $data font data * @access protected * @since 4.5.000 (2009-01-02) */ protected function setFontSubBuffer($font, $key, $data) { if (!isset($this->fonts[$font])) { $this->setFontBuffer($font, array()); } if ($this->diskcache) { $tmpfont = $this->getFontBuffer($font); $tmpfont[$key] = $data; $this->writeDiskCache($this->fonts[$font], serialize($tmpfont)); } else { $this->fonts[$font][$key] = $data; } } /** * Get font buffer content. * @param string $font font key * @return string font buffer content or false in case of error * @access protected * @since 4.5.000 (2009-01-02) */ protected function getFontBuffer($font) { if ($this->diskcache AND isset($this->fonts[$font])) { return unserialize($this->readDiskCache($this->fonts[$font])); } elseif (isset($this->fonts[$font])) { return $this->fonts[$font]; } return false; } /** * Move a page to a previous position. * @param int $frompage number of the source page * @param int $topage number of the destination page (must be less than $frompage) * @return true in case of success, false in case of error. * @access public * @since 4.5.000 (2009-01-02) */ public function movePage($frompage, $topage) { if (($frompage > $this->numpages) OR ($frompage <= $topage)) { return false; } if ($frompage == $this->page) { // close the page before moving it $this->endPage(); } // move all page-related states $tmppage = $this->pages[$frompage]; $tmppagedim = $this->pagedim[$frompage]; $tmppagelen = $this->pagelen[$frompage]; $tmpintmrk = $this->intmrk[$frompage]; $tmpbordermrk = $this->bordermrk[$frompage]; $tmpcntmrk = $this->cntmrk[$frompage]; if (isset($this->footerpos[$frompage])) { $tmpfooterpos = $this->footerpos[$frompage]; } if (isset($this->footerlen[$frompage])) { $tmpfooterlen = $this->footerlen[$frompage]; } if (isset($this->transfmrk[$frompage])) { $tmptransfmrk = $this->transfmrk[$frompage]; } if (isset($this->PageAnnots[$frompage])) { $tmpannots = $this->PageAnnots[$frompage]; } if (isset($this->newpagegroup[$frompage])) { $tmpnewpagegroup = $this->newpagegroup[$frompage]; } for ($i = $frompage; $i > $topage; --$i) { $j = $i - 1; // shift pages down $this->pages[$i] = $this->pages[$j]; $this->pagedim[$i] = $this->pagedim[$j]; $this->pagelen[$i] = $this->pagelen[$j]; $this->intmrk[$i] = $this->intmrk[$j]; $this->bordermrk[$i] = $this->bordermrk[$j]; $this->cntmrk[$i] = $this->cntmrk[$j]; if (isset($this->footerpos[$j])) { $this->footerpos[$i] = $this->footerpos[$j]; } elseif (isset($this->footerpos[$i])) { unset($this->footerpos[$i]); } if (isset($this->footerlen[$j])) { $this->footerlen[$i] = $this->footerlen[$j]; } elseif (isset($this->footerlen[$i])) { unset($this->footerlen[$i]); } if (isset($this->transfmrk[$j])) { $this->transfmrk[$i] = $this->transfmrk[$j]; } elseif (isset($this->transfmrk[$i])) { unset($this->transfmrk[$i]); } if (isset($this->PageAnnots[$j])) { $this->PageAnnots[$i] = $this->PageAnnots[$j]; } elseif (isset($this->PageAnnots[$i])) { unset($this->PageAnnots[$i]); } if (isset($this->newpagegroup[$j])) { $this->newpagegroup[$i] = $this->newpagegroup[$j]; } elseif (isset($this->newpagegroup[$i])) { unset($this->newpagegroup[$i]); } } $this->pages[$topage] = $tmppage; $this->pagedim[$topage] = $tmppagedim; $this->pagelen[$topage] = $tmppagelen; $this->intmrk[$topage] = $tmpintmrk; $this->bordermrk[$topage] = $tmpbordermrk; $this->cntmrk[$topage] = $tmpcntmrk; if (isset($tmpfooterpos)) { $this->footerpos[$topage] = $tmpfooterpos; } elseif (isset($this->footerpos[$topage])) { unset($this->footerpos[$topage]); } if (isset($tmpfooterlen)) { $this->footerlen[$topage] = $tmpfooterlen; } elseif (isset($this->footerlen[$topage])) { unset($this->footerlen[$topage]); } if (isset($tmptransfmrk)) { $this->transfmrk[$topage] = $tmptransfmrk; } elseif (isset($this->transfmrk[$topage])) { unset($this->transfmrk[$topage]); } if (isset($tmpannots)) { $this->PageAnnots[$topage] = $tmpannots; } elseif (isset($this->PageAnnots[$topage])) { unset($this->PageAnnots[$topage]); } if (isset($tmpnewpagegroup)) { $this->newpagegroup[$topage] = $tmpnewpagegroup; } elseif (isset($this->newpagegroup[$topage])) { unset($this->newpagegroup[$topage]); } // adjust outlines $tmpoutlines = $this->outlines; foreach ($tmpoutlines as $key => $outline) { if (($outline['p'] >= $topage) AND ($outline['p'] < $frompage)) { $this->outlines[$key]['p'] = $outline['p'] + 1; } elseif ($outline['p'] == $frompage) { $this->outlines[$key]['p'] = $topage; } } // adjust links $tmplinks = $this->links; foreach ($tmplinks as $key => $link) { if (($link[0] >= $topage) AND ($link[0] < $frompage)) { $this->links[$key][0] = $link[0] + 1; } elseif ($link[0] == $frompage) { $this->links[$key][0] = $topage; } } // adjust javascript $tmpjavascript = $this->javascript; global $jfrompage, $jtopage; $jfrompage = $frompage; $jtopage = $topage; $this->javascript = preg_replace_callback('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/', create_function('$matches', 'global $jfrompage, $jtopage; $pagenum = intval($matches[3]) + 1; if (($pagenum >= $jtopage) AND ($pagenum < $jfrompage)) { $newpage = ($pagenum + 1); } elseif ($pagenum == $jfrompage) { $newpage = $jtopage; } else { $newpage = $pagenum; } --$newpage; return "this.addField(\'".$matches[1]."\',\'".$matches[2]."\',".$newpage."";'), $tmpjavascript); // return to last page $this->lastPage(true); return true; } /** * Remove the specified page. * @param int $page page to remove * @return true in case of success, false in case of error. * @access public * @since 4.6.004 (2009-04-23) */ public function deletePage($page) { if (($page < 1) OR ($page > $this->numpages)) { return false; } // delete current page unset($this->pages[$page]); unset($this->pagedim[$page]); unset($this->pagelen[$page]); unset($this->intmrk[$page]); unset($this->bordermrk[$page]); unset($this->cntmrk[$page]); if (isset($this->footerpos[$page])) { unset($this->footerpos[$page]); } if (isset($this->footerlen[$page])) { unset($this->footerlen[$page]); } if (isset($this->transfmrk[$page])) { unset($this->transfmrk[$page]); } if (isset($this->PageAnnots[$page])) { unset($this->PageAnnots[$page]); } if (isset($this->newpagegroup[$page])) { unset($this->newpagegroup[$page]); } if (isset($this->pageopen[$page])) { unset($this->pageopen[$page]); } // update remaining pages for ($i = $page; $i < $this->numpages; ++$i) { $j = $i + 1; // shift pages $this->pages[$i] = $this->pages[$j]; $this->pagedim[$i] = $this->pagedim[$j]; $this->pagelen[$i] = $this->pagelen[$j]; $this->intmrk[$i] = $this->intmrk[$j]; $this->bordermrk[$i] = $this->bordermrk[$j]; $this->cntmrk[$i] = $this->cntmrk[$j]; if (isset($this->footerpos[$j])) { $this->footerpos[$i] = $this->footerpos[$j]; } elseif (isset($this->footerpos[$i])) { unset($this->footerpos[$i]); } if (isset($this->footerlen[$j])) { $this->footerlen[$i] = $this->footerlen[$j]; } elseif (isset($this->footerlen[$i])) { unset($this->footerlen[$i]); } if (isset($this->transfmrk[$j])) { $this->transfmrk[$i] = $this->transfmrk[$j]; } elseif (isset($this->transfmrk[$i])) { unset($this->transfmrk[$i]); } if (isset($this->PageAnnots[$j])) { $this->PageAnnots[$i] = $this->PageAnnots[$j]; } elseif (isset($this->PageAnnots[$i])) { unset($this->PageAnnots[$i]); } if (isset($this->newpagegroup[$j])) { $this->newpagegroup[$i] = $this->newpagegroup[$j]; } elseif (isset($this->newpagegroup[$i])) { unset($this->newpagegroup[$i]); } if (isset($this->pageopen[$j])) { $this->pageopen[$i] = $this->pageopen[$j]; } elseif (isset($this->pageopen[$i])) { unset($this->pageopen[$i]); } } // remove last page unset($this->pages[$this->numpages]); unset($this->pagedim[$this->numpages]); unset($this->pagelen[$this->numpages]); unset($this->intmrk[$this->numpages]); unset($this->bordermrk[$this->numpages]); unset($this->cntmrk[$this->numpages]); if (isset($this->footerpos[$this->numpages])) { unset($this->footerpos[$this->numpages]); } if (isset($this->footerlen[$this->numpages])) { unset($this->footerlen[$this->numpages]); } if (isset($this->transfmrk[$this->numpages])) { unset($this->transfmrk[$this->numpages]); } if (isset($this->PageAnnots[$this->numpages])) { unset($this->PageAnnots[$this->numpages]); } if (isset($this->newpagegroup[$this->numpages])) { unset($this->newpagegroup[$this->numpages]); } if (isset($this->pageopen[$this->numpages])) { unset($this->pageopen[$this->numpages]); } --$this->numpages; $this->page = $this->numpages; // adjust outlines $tmpoutlines = $this->outlines; foreach ($tmpoutlines as $key => $outline) { if ($outline['p'] > $page) { $this->outlines[$key]['p'] = $outline['p'] - 1; } elseif ($outline['p'] == $page) { unset($this->outlines[$key]); } } // adjust links $tmplinks = $this->links; foreach ($tmplinks as $key => $link) { if ($link[0] > $page) { $this->links[$key][0] = $link[0] - 1; } elseif ($link[0] == $page) { unset($this->links[$key]); } } // adjust javascript $tmpjavascript = $this->javascript; global $jpage; $jpage = $page; $this->javascript = preg_replace_callback('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/', create_function('$matches', 'global $jpage; $pagenum = intval($matches[3]) + 1; if ($pagenum >= $jpage) { $newpage = ($pagenum - 1); } elseif ($pagenum == $jpage) { $newpage = 1; } else { $newpage = $pagenum; } --$newpage; return "this.addField(\'".$matches[1]."\',\'".$matches[2]."\',".$newpage."";'), $tmpjavascript); // return to last page $this->lastPage(true); return true; } /** * Clone the specified page to a new page. * @param int $page number of page to copy (0 = current page) * @return true in case of success, false in case of error. * @access public * @since 4.9.015 (2010-04-20) */ public function copyPage($page=0) { if ($page == 0) { // default value $page = $this->page; } if (($page < 1) OR ($page > $this->numpages)) { return false; } if ($page == $this->page) { // close the page before cloning it $this->endPage(); } // copy all page-related states ++$this->numpages; $this->page = $this->numpages; $this->pages[$this->page] = $this->pages[$page]; $this->pagedim[$this->page] = $this->pagedim[$page]; $this->pagelen[$this->page] = $this->pagelen[$page]; $this->intmrk[$this->page] = $this->intmrk[$page]; $this->bordermrk[$this->page] = $this->bordermrk[$page]; $this->cntmrk[$this->page] = $this->cntmrk[$page]; $this->pageopen[$this->page] = false; if (isset($this->footerpos[$page])) { $this->footerpos[$this->page] = $this->footerpos[$page]; } if (isset($this->footerlen[$page])) { $this->footerlen[$this->page] = $this->footerlen[$page]; } if (isset($this->transfmrk[$page])) { $this->transfmrk[$this->page] = $this->transfmrk[$page]; } if (isset($this->PageAnnots[$page])) { $this->PageAnnots[$this->page] = $this->PageAnnots[$page]; } if (isset($this->newpagegroup[$page])) { $this->newpagegroup[$this->page] = $this->newpagegroup[$page]; } // copy outlines $tmpoutlines = $this->outlines; foreach ($tmpoutlines as $key => $outline) { if ($outline['p'] == $page) { $this->outlines[] = array('t' => $outline['t'], 'l' => $outline['l'], 'y' => $outline['y'], 'p' => $this->page); } } // copy links $tmplinks = $this->links; foreach ($tmplinks as $key => $link) { if ($link[0] == $page) { $this->links[] = array($this->page, $link[1]); } } // return to last page $this->lastPage(true); return true; } /** * Output a Table of Content Index (TOC). * Before calling this method you have to open the page using the addTOCPage() method. * After calling this method you have to call endTOCPage() to close the TOC page. * You can override this method to achieve different styles. * @param int $page page number where this TOC should be inserted (leave empty for current page). * @param string $numbersfont set the font for page numbers (please use monospaced font for better alignment). * @param string $filler string used to fill the space between text and page number. * @param string $toc_name name to use for TOC bookmark. * @access public * @author Nicola Asuni * @since 4.5.000 (2009-01-02) * @see addTOCPage(), endTOCPage(), addHTMLTOC() */ public function addTOC($page='', $numbersfont='', $filler='.', $toc_name='TOC') { $fontsize = $this->FontSizePt; $fontfamily = $this->FontFamily; $fontstyle = $this->FontStyle; $w = $this->w - $this->lMargin - $this->rMargin; $spacer = $this->GetStringWidth(chr(32)) * 4; $page_first = $this->getPage(); $lmargin = $this->lMargin; $rmargin = $this->rMargin; $x_start = $this->GetX(); $current_page = $this->page; $current_column = $this->current_column; if ($this->empty_string($numbersfont)) { $numbersfont = $this->default_monospaced_font; } if ($this->empty_string($filler)) { $filler = ' '; } if ($this->empty_string($page)) { $gap = ' '; } else { $gap = ''; if ($page < 1) { $page = 1; } } foreach ($this->outlines as $key => $outline) { if ($this->rtl) { $aligntext = 'R'; $alignnum = 'L'; } else { $aligntext = 'L'; $alignnum = 'R'; } if ($outline['l'] == 0) { $this->SetFont($fontfamily, $fontstyle.'B', $fontsize); } else { $this->SetFont($fontfamily, $fontstyle, $fontsize - $outline['l']); } // check for page break $this->checkPageBreak(($this->FontSize * $this->cell_height_ratio)); // set margins and X position if (($this->page == $current_page) AND ($this->current_column == $current_column)) { $this->lMargin = $lmargin; $this->rMargin = $rmargin; } else { if ($this->current_column != $current_column) { if ($this->rtl) { $x_start = $this->w - $this->columns[$this->current_column]['x']; } else { $x_start = $this->columns[$this->current_column]['x']; } } $lmargin = $this->lMargin; $rmargin = $this->rMargin; $current_page = $this->page; $current_column = $this->current_column; } $this->SetX($x_start); $indent = ($spacer * $outline['l']); if ($this->rtl) { $this->rMargin += $indent; $this->x -= $indent; } else { $this->lMargin += $indent; $this->x += $indent; } $link = $this->AddLink(); $this->SetLink($link, 0, $outline['p']); // write the text $this->Write(0, $outline['t'], $link, 0, $aligntext, false, 0, false, false, 0); $this->SetFont($numbersfont, $fontstyle, $fontsize); if ($this->empty_string($page)) { $pagenum = $outline['p']; } else { // placemark to be replaced with the correct number $pagenum = '{#'.($outline['p']).'}'; if ($this->isUnicodeFont()) { $pagenum = '{'.$pagenum.'}'; } } $numwidth = $this->GetStringWidth($pagenum); if ($this->rtl) { $tw = $this->x - $this->lMargin; } else { $tw = $this->w - $this->rMargin - $this->x; } $fw = $tw - $numwidth - $this->GetStringWidth(chr(32)); $numfills = floor($fw / $this->GetStringWidth($filler)); if ($numfills > 0) { $rowfill = str_repeat($filler, $numfills); } else { $rowfill = ''; } if ($this->rtl) { $pagenum = $pagenum.$gap.$rowfill.' '; } else { $pagenum = ' '.$rowfill.$gap.$pagenum; } // write the number $this->Cell($tw, 0, $pagenum, 0, 1, $alignnum, 0, $link, 0); } $page_last = $this->getPage(); $numpages = $page_last - $page_first + 1; if (!$this->empty_string($page)) { for ($p = $page_first; $p <= $page_last; ++$p) { // get page data $temppage = $this->getPageBuffer($p); for ($n = 1; $n <= $this->numpages; ++$n) { // update page numbers $k = '{#'.$n.'}'; $ku = '{'.$k.'}'; $alias_a = $this->_escape($k); $alias_au = $this->_escape($ku); if ($this->isunicode) { $alias_b = $this->_escape($this->UTF8ToLatin1($k)); $alias_bu = $this->_escape($this->UTF8ToLatin1($ku)); $alias_c = $this->_escape($this->utf8StrRev($k, false, $this->tmprtl)); $alias_cu = $this->_escape($this->utf8StrRev($ku, false, $this->tmprtl)); } if ($n >= $page) { $np = $n + $numpages; } else { $np = $n; } $ns = $this->formatTOCPageNumber($np); $nu = $ns; $sdiff = strlen($k) - strlen($ns) - 1; $sdiffu = strlen($ku) - strlen($ns) - 1; $sfill = str_repeat($filler, $sdiff); $sfillu = str_repeat($filler, $sdiffu); if ($this->rtl) { $ns = $ns.' '.$sfill; $nu = $nu.' '.$sfillu; } else { $ns = $sfill.' '.$ns; $nu = $sfillu.' '.$nu; } $nu = $this->UTF8ToUTF16BE($nu, false); $temppage = str_replace($alias_au, $nu, $temppage); if ($this->isunicode) { $temppage = str_replace($alias_bu, $nu, $temppage); $temppage = str_replace($alias_cu, $nu, $temppage); $temppage = str_replace($alias_b, $ns, $temppage); $temppage = str_replace($alias_c, $ns, $temppage); } $temppage = str_replace($alias_a, $ns, $temppage); } // save changes $this->setPageBuffer($p, $temppage); } // move pages $this->Bookmark($toc_name, 0, 0, $page_first); for ($i = 0; $i < $numpages; ++$i) { $this->movePage($page_last, $page); } } } /** * Output a Table Of Content Index (TOC) using HTML templates. * Before calling this method you have to open the page using the addTOCPage() method. * After calling this method you have to call endTOCPage() to close the TOC page. * @param int $page page number where this TOC should be inserted (leave empty for current page). * @param string $toc_name name to use for TOC bookmark. * @param array $templates array of html templates. Use: #TOC_DESCRIPTION# for bookmark title, #TOC_PAGE_NUMBER# for page number. * @param boolean $correct_align if true correct the number alignment (numbers must be in monospaced font like courier and right aligned on LTR, or left aligned on RTL) * @access public * @author Nicola Asuni * @since 5.0.001 (2010-05-06) * @see addTOCPage(), endTOCPage(), addTOC() */ public function addHTMLTOC($page='', $toc_name='TOC', $templates=array(), $correct_align=true) { $prev_htmlLinkColorArray = $this->htmlLinkColorArray; $prev_htmlLinkFontStyle = $this->htmlLinkFontStyle; // set new style for link $this->htmlLinkColorArray = array(); $this->htmlLinkFontStyle = ''; $page_first = $this->getPage(); // get the font type used for numbers in each template $current_font = $this->FontFamily; foreach ($templates as $level => $html) { $dom = $this->getHtmlDomArray($html); foreach ($dom as $key => $value) { if ($value['value'] == '#TOC_PAGE_NUMBER#') { $this->SetFont($dom[($key - 1)]['fontname']); $templates['F'.$level] = $this->isUnicodeFont(); } } } $this->SetFont($current_font); foreach ($this->outlines as $key => $outline) { // get HTML template $row = $templates[$outline['l']]; if ($this->empty_string($page)) { $pagenum = $outline['p']; } else { // placemark to be replaced with the correct number $pagenum = '{#'.($outline['p']).'}'; if ($templates['F'.$outline['l']]) { $pagenum = '{'.$pagenum.'}'; } } // replace templates with current values $row = str_replace('#TOC_DESCRIPTION#', $outline['t'], $row); $row = str_replace('#TOC_PAGE_NUMBER#', $pagenum, $row); // add link to page $row = '<a href="#'.$outline['p'].'">'.$row.'</a>'; // write bookmark entry $this->writeHTML($row, false, false, true, false, ''); } // restore link styles $this->htmlLinkColorArray = $prev_htmlLinkColorArray; $this->htmlLinkFontStyle = $prev_htmlLinkFontStyle; // move TOC page and replace numbers $page_last = $this->getPage(); $numpages = $page_last - $page_first + 1; if (!$this->empty_string($page)) { for ($p = $page_first; $p <= $page_last; ++$p) { // get page data $temppage = $this->getPageBuffer($p); for ($n = 1; $n <= $this->numpages; ++$n) { // update page numbers $k = '{#'.$n.'}'; $ku = '{'.$k.'}'; $alias_a = $this->_escape($k); $alias_au = $this->_escape('{'.$k.'}'); if ($this->isunicode) { $alias_b = $this->_escape($this->UTF8ToLatin1($k)); $alias_bu = $this->_escape($this->UTF8ToLatin1($ku)); $alias_c = $this->_escape($this->utf8StrRev($k, false, $this->tmprtl)); $alias_cu = $this->_escape($this->utf8StrRev($ku, false, $this->tmprtl)); } if ($n >= $page) { $np = $n + $numpages; } else { $np = $n; } $ns = $this->formatTOCPageNumber($np); $nu = $ns; if ($correct_align) { $sdiff = strlen($k) - strlen($ns); $sdiffu = strlen($ku) - strlen($ns); $sfill = str_repeat(' ', $sdiff); $sfillu = str_repeat(' ', $sdiffu); if ($this->rtl) { $ns = $ns.$sfill; $nu = $nu.$sfillu; } else { $ns = $sfill.$ns; $nu = $sfillu.$nu; } } $nu = $this->UTF8ToUTF16BE($nu, false); $temppage = str_replace($alias_au, $nu, $temppage); if ($this->isunicode) { $temppage = str_replace($alias_bu, $nu, $temppage); $temppage = str_replace($alias_cu, $nu, $temppage); $temppage = str_replace($alias_b, $ns, $temppage); $temppage = str_replace($alias_c, $ns, $temppage); } $temppage = str_replace($alias_a, $ns, $temppage); } // save changes $this->setPageBuffer($p, $temppage); } // move pages $this->Bookmark($toc_name, 0, 0, $page_first); for ($i = 0; $i < $numpages; ++$i) { $this->movePage($page_last, $page); } } } /** * Stores a copy of the current TCPDF object used for undo operation. * @access public * @since 4.5.029 (2009-03-19) */ public function startTransaction() { if (isset($this->objcopy)) { // remove previous copy $this->commitTransaction(); } // record current page number and Y position $this->start_transaction_page = $this->page; $this->start_transaction_y = $this->y; // clone current object $this->objcopy = $this->objclone($this); } /** * Delete the copy of the current TCPDF object used for undo operation. * @access public * @since 4.5.029 (2009-03-19) */ public function commitTransaction() { if (isset($this->objcopy)) { $this->objcopy->_destroy(true, true); unset($this->objcopy); } } /** * This method allows to undo the latest transaction by returning the latest saved TCPDF object with startTransaction(). * @param boolean $self if true restores current class object to previous state without the need of reassignment via the returned value. * @return TCPDF object. * @access public * @since 4.5.029 (2009-03-19) */ public function rollbackTransaction($self=false) { if (isset($this->objcopy)) { if (isset($this->objcopy->diskcache) AND $this->objcopy->diskcache) { // truncate files to previous values foreach ($this->objcopy->cache_file_length as $file => $length) { $file = substr($file, 1); $handle = fopen($file, 'r+'); ftruncate($handle, $length); } } $this->_destroy(true, true); if ($self) { $objvars = get_object_vars($this->objcopy); foreach ($objvars as $key => $value) { $this->$key = $value; } } return $this->objcopy; } return $this; } /** * Creates a copy of a class object * @param object $object class object to be cloned * @return cloned object * @access public * @since 4.5.029 (2009-03-19) */ public function objclone($object) { return @clone($object); } /** * Determine whether a string is empty. * @param string $str string to be checked * @return boolean true if string is empty * @access public * @since 4.5.044 (2009-04-16) */ public function empty_string($str) { return (is_null($str) OR (is_string($str) AND (strlen($str) == 0))); } /** * Find position of last occurrence of a substring in a string * @param string $haystack The string to search in. * @param string $needle substring to search. * @param int $offset May be specified to begin searching an arbitrary number of characters into the string. * @return Returns the position where the needle exists. Returns FALSE if the needle was not found. * @access public * @since 4.8.038 (2010-03-13) */ public function revstrpos($haystack, $needle, $offset = 0) { $length = strlen($haystack); $offset = ($offset > 0)?($length - $offset):abs($offset); $pos = strpos(strrev($haystack), strrev($needle), $offset); return ($pos === false)?false:($length - $pos - strlen($needle)); } // --- MULTI COLUMNS METHODS ----------------------- /** * Set multiple columns of the same size * @param int $numcols number of columns (set to zero to disable columns mode) * @param int $width column width * @param int $y column starting Y position (leave empty for current Y position) * @access public * @since 4.9.001 (2010-03-28) */ public function setEqualColumns($numcols=0, $width=0, $y='') { $this->columns = array(); if ($numcols < 2) { $numcols = 0; $this->columns = array(); } else { // maximum column width $maxwidth = ($this->w - $this->original_lMargin - $this->original_rMargin) / $numcols; if (($width == 0) OR ($width > $maxwidth)) { $width = $maxwidth; } if ($this->empty_string($y)) { $y = $this->y; } // space between columns $space = (($this->w - $this->original_lMargin - $this->original_rMargin - ($numcols * $width)) / ($numcols - 1)); // fill the columns array (with, space, starting Y position) for ($i = 0; $i < $numcols; ++$i) { $this->columns[$i] = array('w' => $width, 's' => $space, 'y' => $y); } } $this->num_columns = $numcols; $this->current_column = 0; $this->column_start_page = $this->page; } /** * Set columns array. * Each column is represented by and array with the following keys: (w = width, s = space between columns, y = column top position). * @param array $columns * @access public * @since 4.9.001 (2010-03-28) */ public function setColumnsArray($columns) { $this->columns = $columns; $this->num_columns = count($columns); $this->current_column = 0; $this->column_start_page = $this->page; } /** * Set position at a given column * @param int $col column number (from 0 to getNumberOfColumns()-1); empty string = current column. * @access public * @since 4.9.001 (2010-03-28) */ public function selectColumn($col='') { if (is_string($col)) { $col = $this->current_column; } elseif($col >= $this->num_columns) { $col = 0; } $xshift = 0; $enable_thead = false; if ($this->num_columns > 1) { if ($col != $this->current_column) { // move Y pointer at the top of the column if ($this->column_start_page == $this->page) { $this->y = $this->columns[$col]['y']; } else { $this->y = $this->tMargin; } // Avoid to write table headers more than once if (($this->page > $this->maxselcol['page']) OR (($this->page == $this->maxselcol['page']) AND ($col > $this->maxselcol['column']))) { $enable_thead = true; $this->maxselcol['page'] = $this->page; $this->maxselcol['column'] = $col; } } $xshift = $this->colxshift; // set X position of the current column by case $listindent = ($this->listindentlevel * $this->listindent); $colpos = ($col * ($this->columns[$col]['w'] + $this->columns[$col]['s'])); if ($this->rtl) { $x = $this->w - $this->original_rMargin - $colpos; $this->rMargin = ($this->w - $x + $listindent); $this->lMargin = ($x - $this->columns[$col]['w']); $this->x = $x - $listindent; } else { $x = $this->original_lMargin + $colpos; $this->lMargin = ($x + $listindent); $this->rMargin = ($this->w - $x - $this->columns[$col]['w']); $this->x = $x + $listindent; } $this->columns[$col]['x'] = $x; } $this->current_column = $col; // fix for HTML mode $this->newline = true; // print HTML table header (if any) if ((!$this->empty_string($this->thead)) AND (!$this->inthead)) { if ($enable_thead) { // print table header $this->writeHTML($this->thead, false, false, false, false, ''); $this->y += $xshift['s']; // store end of header position if (!isset($this->columns[$col]['th'])) { $this->columns[$col]['th'] = array(); } $this->columns[$col]['th']['\''.$this->page.'\''] = $this->y; $this->lasth = 0; } elseif (isset($this->columns[$col]['th']['\''.$this->page.'\''])) { $this->y = $this->columns[$col]['th']['\''.$this->page.'\'']; } } // account for an html table cell over multiple columns if ($this->rtl) { $this->rMargin += $xshift['x']; $this->x -= ($xshift['x'] + $xshift['p']); } else { $this->lMargin += $xshift['x']; $this->x += $xshift['x'] + $xshift['p']; } } /** * Return the current column number * @return int current column number * @access public * @since 5.5.011 (2010-07-08) */ public function getColumn() { return $this->current_column; } /** * Return the current number of columns. * @return int number of columns * @access public * @since 5.8.018 (2010-08-25) */ public function getNumberOfColumns() { return $this->num_columns; } /** * Serialize an array of parameters to be used with TCPDF tag in HTML code. * @param array $pararray parameters array * @return sting containing serialized data * @access public * @since 4.9.006 (2010-04-02) */ public function serializeTCPDFtagParameters($pararray) { return urlencode(serialize($pararray)); } /** * Set Text rendering mode. * @param int $stroke outline size in user units (0 = disable). * @param boolean $fill if true fills the text (default). * @param boolean $clip if true activate clipping mode * @access public * @since 4.9.008 (2009-04-02) */ public function setTextRenderingMode($stroke=0, $fill=true, $clip=false) { // Ref.: PDF 32000-1:2008 - 9.3.6 Text Rendering Mode // convert text rendering parameters if ($stroke < 0) { $stroke = 0; } if ($fill === true) { if ($stroke > 0) { if ($clip === true) { // Fill, then stroke text and add to path for clipping $textrendermode = 6; } else { // Fill, then stroke text $textrendermode = 2; } $textstrokewidth = $stroke; } else { if ($clip === true) { // Fill text and add to path for clipping $textrendermode = 4; } else { // Fill text $textrendermode = 0; } } } else { if ($stroke > 0) { if ($clip === true) { // Stroke text and add to path for clipping $textrendermode = 5; } else { // Stroke text $textrendermode = 1; } $textstrokewidth = $stroke; } else { if ($clip === true) { // Add text to path for clipping $textrendermode = 7; } else { // Neither fill nor stroke text (invisible) $textrendermode = 3; } } } $this->textrendermode = $textrendermode; $this->textstrokewidth = $stroke * $this->k; } /** * Returns an array of chars containing soft hyphens. * @param array $word array of chars * @param array $patterns Array of hypenation patterns. * @param array $dictionary Array of words to be returned without applying the hyphenation algoritm. * @param int $leftmin Minimum number of character to leave on the left of the word without applying the hyphens. * @param int $rightmin Minimum number of character to leave on the right of the word without applying the hyphens. * @param int $charmin Minimum word lenght to apply the hyphenation algoritm. * @param int $charmax Maximum lenght of broken piece of word. * @return array text with soft hyphens * @author Nicola Asuni * @since 4.9.012 (2010-04-12) * @access protected */ protected function hyphenateWord($word, $patterns, $dictionary=array(), $leftmin=1, $rightmin=2, $charmin=1, $charmax=8) { $hyphenword = array(); // hyphens positions $numchars = count($word); if ($numchars <= $charmin) { return $word; } $word_string = $this->UTF8ArrSubString($word); // some words will be returned as-is $pattern = '/^([a-zA-Z0-9_\.\-]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/'; if (preg_match($pattern, $word_string) > 0) { // email return $word; } $pattern = '/(([a-zA-Z0-9\-]+\.)?)((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/'; if (preg_match($pattern, $word_string) > 0) { // URL return $word; } if (isset($dictionary[$word_string])) { return $this->UTF8StringToArray($dictionary[$word_string]); } // suround word with '_' characters $tmpword = array_merge(array(95), $word, array(95)); $tmpnumchars = $numchars + 2; $maxpos = $tmpnumchars - $charmin; for ($pos = 0; $pos < $maxpos; ++$pos) { $imax = min(($tmpnumchars - $pos), $charmax); for ($i = $charmin; $i <= $imax; ++$i) { $subword = strtolower($this->UTF8ArrSubString($tmpword, $pos, $pos + $i)); if (isset($patterns[$subword])) { $pattern = $this->UTF8StringToArray($patterns[$subword]); $pattern_length = count($pattern); $digits = 1; for ($j = 0; $j < $pattern_length; ++$j) { // check if $pattern[$j] is a number if (($pattern[$j] >= 48) AND ($pattern[$j] <= 57)) { if ($j == 0) { $zero = $pos - 1; } else { $zero = $pos + $j - $digits; } if (!isset($hyphenword[$zero]) OR ($hyphenword[$zero] != $pattern[$j])) { $hyphenword[$zero] = $this->unichr($pattern[$j]); } ++$digits; } } } } } $inserted = 0; $maxpos = $numchars - $rightmin; for($i = $leftmin; $i <= $maxpos; ++$i) { if(isset($hyphenword[$i]) AND (($hyphenword[$i] % 2) != 0)) { // 173 = soft hyphen character array_splice($word, $i + $inserted, 0, 173); ++$inserted; } } return $word; } /** * Returns an array of hyphenation patterns. * @param string $file TEX file containing hypenation patterns. TEX pattrns can be downloaded from http://www.ctan.org/tex-archive/language/hyph-utf8/tex/generic/hyph-utf8/patterns/ * @return array of hyphenation patterns * @author Nicola Asuni * @since 4.9.012 (2010-04-12) * @access public */ public function getHyphenPatternsFromTEX($file) { // TEX patterns are available at: // http://www.ctan.org/tex-archive/language/hyph-utf8/tex/generic/hyph-utf8/patterns/ $data = file_get_contents($file); $patterns = array(); // remove comments $data = preg_replace('/\%[^\n]*/', '', $data); // extract the patterns part preg_match('/\\\\patterns\{([^\}]*)\}/i', $data, $matches); $data = trim(substr($matches[0], 10, -1)); // extract each pattern $patterns_array = preg_split('/[\s]+/', $data); // create new language array of patterns $patterns = array(); foreach($patterns_array as $val) { if (!$this->empty_string($val)) { $val = trim($val); $val = str_replace('\'', '\\\'', $val); $key = preg_replace('/[0-9]+/', '', $val); $patterns[$key] = $val; } } return $patterns; } /** * Returns text with soft hyphens. * @param string $text text to process * @param mixed $patterns Array of hypenation patterns or a TEX file containing hypenation patterns. TEX patterns can be downloaded from http://www.ctan.org/tex-archive/language/hyph-utf8/tex/generic/hyph-utf8/patterns/ * @param array $dictionary Array of words to be returned without applying the hyphenation algoritm. * @param int $leftmin Minimum number of character to leave on the left of the word without applying the hyphens. * @param int $rightmin Minimum number of character to leave on the right of the word without applying the hyphens. * @param int $charmin Minimum word lenght to apply the hyphenation algoritm. * @param int $charmax Maximum lenght of broken piece of word. * @return array text with soft hyphens * @author Nicola Asuni * @since 4.9.012 (2010-04-12) * @access public */ public function hyphenateText($text, $patterns, $dictionary=array(), $leftmin=1, $rightmin=2, $charmin=1, $charmax=8) { global $unicode; $text = $this->unhtmlentities($text); $word = array(); // last word $txtarr = array(); // text to be returned $intag = false; // true if we are inside an HTML tag if (!is_array($patterns)) { $patterns = $this->getHyphenPatternsFromTEX($patterns); } // get array of characters $unichars = $this->UTF8StringToArray($text); // for each char foreach ($unichars as $char) { if ((!$intag) AND $unicode[$char] == 'L') { // letter character $word[] = $char; } else { // other type of character if (!$this->empty_string($word)) { // hypenate the word $txtarr = array_merge($txtarr, $this->hyphenateWord($word, $patterns, $dictionary, $leftmin, $rightmin, $charmin, $charmax)); $word = array(); } $txtarr[] = $char; if (chr($char) == '<') { // we are inside an HTML tag $intag = true; } elseif ($intag AND (chr($char) == '>')) { // end of HTML tag $intag = false; } } } if (!$this->empty_string($word)) { // hypenate the word $txtarr = array_merge($txtarr, $this->hyphenateWord($word, $patterns, $dictionary, $leftmin, $rightmin, $charmin, $charmax)); } // convert char array to string and return return $this->UTF8ArrSubString($txtarr); } /** * Enable/disable rasterization of vector images using ImageMagick library. * @param boolean $mode if true enable rasterization, false otherwise. * @access public * @since 5.0.000 (2010-04-27) */ public function setRasterizeVectorImages($mode) { $this->rasterize_vector_images = $mode; } /** * Get the Path-Painting Operators. * @param string $style Style of rendering. Possible values are: * <ul> * <li>S or D: Stroke the path.</li> * <li>s or d: Close and stroke the path.</li> * <li>f or F: Fill the path, using the nonzero winding number rule to determine the region to fill.</li> * <li>f* or F*: Fill the path, using the even-odd rule to determine the region to fill.</li> * <li>B or FD or DF: Fill and then stroke the path, using the nonzero winding number rule to determine the region to fill.</li> * <li>B* or F*D or DF*: Fill and then stroke the path, using the even-odd rule to determine the region to fill.</li> * <li>b or fd or df: Close, fill, and then stroke the path, using the nonzero winding number rule to determine the region to fill.</li> * <li>b or f*d or df*: Close, fill, and then stroke the path, using the even-odd rule to determine the region to fill.</li> * <li>CNZ: Clipping mode using the even-odd rule to determine which regions lie inside the clipping path.</li> * <li>CEO: Clipping mode using the nonzero winding number rule to determine which regions lie inside the clipping path</li> * <li>n: End the path object without filling or stroking it.</li> * </ul> * @param string $default default style * @param boolean $mode if true enable rasterization, false otherwise. * @author Nicola Asuni * @access protected * @since 5.0.000 (2010-04-30) */ protected function getPathPaintOperator($style, $default='S') { $op = ''; switch($style) { case 'S': case 'D': { $op = 'S'; break; } case 's': case 'd': { $op = 's'; break; } case 'f': case 'F': { $op = 'f'; break; } case 'f*': case 'F*': { $op = 'f*'; break; } case 'B': case 'FD': case 'DF': { $op = 'B'; break; } case 'B*': case 'F*D': case 'DF*': { $op = 'B*'; break; } case 'b': case 'fd': case 'df': { $op = 'b'; break; } case 'b*': case 'f*d': case 'df*': { $op = 'b*'; break; } case 'CNZ': { $op = 'W n'; break; } case 'CEO': { $op = 'W* n'; break; } case 'n': { $op = 'n'; break; } default: { if (!empty($default)) { $op = $this->getPathPaintOperator($default, ''); } else { $op = ''; } } } return $op; } /** * Enable or disable default option for font subsetting. * @param boolean $enable if true enable font subsetting by default. * @author Nicola Asuni * @access public * @since 5.3.002 (2010-06-07) */ public function setFontSubsetting($enable=true) { $this->font_subsetting = $enable ? true : false; } /** * Return the default option for font subsetting. * @return boolean default font subsetting state. * @author Nicola Asuni * @access public * @since 5.3.002 (2010-06-07) */ public function getFontSubsetting() { return $this->font_subsetting; } /** * Left trim the input string * @param string $str string to trim * @param string $replace string that replace spaces. * @return left trimmed string * @author Nicola Asuni * @access public * @since 5.8.000 (2010-08-11) */ public function stringLeftTrim($str, $replace='') { return preg_replace('/^'.$this->re_space['p'].'+/'.$this->re_space['m'], $replace, $str); } /** * Right trim the input string * @param string $str string to trim * @param string $replace string that replace spaces. * @return right trimmed string * @author Nicola Asuni * @access public * @since 5.8.000 (2010-08-11) */ public function stringRightTrim($str, $replace='') { return preg_replace('/'.$this->re_space['p'].'+$/'.$this->re_space['m'], $replace, $str); } /** * Trim the input string * @param string $str string to trim * @param string $replace string that replace spaces. * @return trimmed string * @author Nicola Asuni * @access public * @since 5.8.000 (2010-08-11) */ public function stringTrim($str, $replace='') { $str = $this->stringLeftTrim($str, $replace); $str = $this->stringRightTrim($str, $replace); return $str; } /** * Return true if the current font is unicode type. * @return true for unicode font, false otherwise. * @author Nicola Asuni * @access public * @since 5.8.002 (2010-08-14) */ public function isUnicodeFont() { return (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0')); } /** * Return normalized font name * @param string $fontfamily property string containing font family names * @return string normalized font name * @author Nicola Asuni * @access public * @since 5.8.004 (2010-08-17) */ public function getFontFamilyName($fontfamily) { // remove spaces and symbols $fontfamily = preg_replace('/[^a-z0-9\,]/', '', strtolower($fontfamily)); // extract all font names $fontslist = preg_split('/[,]/', $fontfamily); // find first valid font name foreach ($fontslist as $font) { // replace font variations $font = preg_replace('/italic$/', 'I', $font); $font = preg_replace('/oblique$/', 'I', $font); $font = preg_replace('/bold([I]?)$/', 'B\\1', $font); // replace common family names and core fonts $pattern = array(); $replacement = array(); $pattern[] = '/^serif|^cursive|^fantasy|^timesnewroman/'; $replacement[] = 'times'; $pattern[] = '/^sansserif/'; $replacement[] = 'helvetica'; $pattern[] = '/^monospace/'; $replacement[] = 'courier'; $font = preg_replace($pattern, $replacement, $font); if (in_array(strtolower($font), $this->fontlist) OR in_array($font, $this->fontkeys)) { return $font; } } // return current font as default return $this->CurrentFont['fontkey']; } /** * Start a new XObject Template. * An XObject Template is a PDF block that is a self-contained description of any sequence of graphics objects (including path objects, text objects, and sampled images). * An XObject Template may be painted multiple times, either on several pages or at several locations on the same page and produces the same results each time, subject only to the graphics state at the time it is invoked. * Note: X,Y coordinates will be reset to 0,0. * @param int $w Template width in user units (empty string or zero = page width less margins) * @param int $h Template height in user units (empty string or zero = page height less margins) * @return int the XObject Template ID in case of success or false in case of error. * @author Nicola Asuni * @access public * @since 5.8.017 (2010-08-24) * @see endTemplate(), printTemplate() */ public function startTemplate($w=0, $h=0) { if ($this->inxobj) { // we are already inside an XObject template return false; } $this->inxobj = true; ++$this->n; // XObject ID $this->xobjid = 'XT'.$this->n; // object ID $this->xobjects[$this->xobjid] = array('n' => $this->n); // store current graphic state $this->xobjects[$this->xobjid]['gvars'] = $this->getGraphicVars(); // initialize data $this->xobjects[$this->xobjid]['outdata'] = ''; $this->xobjects[$this->xobjid]['xobjects'] = array(); $this->xobjects[$this->xobjid]['images'] = array(); $this->xobjects[$this->xobjid]['fonts'] = array(); $this->xobjects[$this->xobjid]['annotations'] = array(); // set new environment $this->num_columns = 1; $this->current_column = 0; $this->SetAutoPageBreak(false); if (($w === '') OR ($w <= 0)) { $w = $this->w - $this->lMargin - $this->rMargin; } if (($h === '') OR ($h <= 0)) { $h = $this->h - $this->tMargin - $this->bMargin; } $this->xobjects[$this->xobjid]['w'] = $w; $this->xobjects[$this->xobjid]['h'] = $h; $this->w = $w; $this->h = $h; $this->wPt = $this->w * $this->k; $this->hPt = $this->h * $this->k; $this->fwPt = $this->wPt; $this->fhPt = $this->hPt; $this->x = 0; $this->y = 0; $this->lMargin = 0; $this->rMargin = 0; $this->tMargin = 0; $this->bMargin = 0; return $this->xobjid; } /** * End the current XObject Template started with startTemplate() and restore the previous graphic state. * An XObject Template is a PDF block that is a self-contained description of any sequence of graphics objects (including path objects, text objects, and sampled images). * An XObject Template may be painted multiple times, either on several pages or at several locations on the same page and produces the same results each time, subject only to the graphics state at the time it is invoked. * @return int the XObject Template ID in case of success or false in case of error. * @author Nicola Asuni * @access public * @since 5.8.017 (2010-08-24) * @see startTemplate(), printTemplate() */ public function endTemplate() { if (!$this->inxobj) { // we are not inside a template return false; } $this->inxobj = false; // restore previous graphic state $this->setGraphicVars($this->xobjects[$this->xobjid]['gvars'], true); return $this->xobjid; } /** * Print an XObject Template. * You can print an XObject Template inside the currently opened Template. * An XObject Template is a PDF block that is a self-contained description of any sequence of graphics objects (including path objects, text objects, and sampled images). * An XObject Template may be painted multiple times, either on several pages or at several locations on the same page and produces the same results each time, subject only to the graphics state at the time it is invoked. * @param string $id The ID of XObject Template to print. * @param int $x X position in user units (empty string = current x position) * @param int $y Y position in user units (empty string = current y position) * @param int $w Width in user units (zero = remaining page width) * @param int $h Height in user units (zero = remaining page height) * @param string $align Indicates the alignment of the pointer next to template insertion relative to template height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul> * @param string $palign Allows to center or align the template on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul> * @param boolean $fitonpage if true the template is resized to not exceed page dimensions. * @author Nicola Asuni * @access public * @since 5.8.017 (2010-08-24) * @see startTemplate(), endTemplate() */ public function printTemplate($id, $x='', $y='', $w=0, $h=0, $align='', $palign='', $fitonpage=false) { if (!isset($this->xobjects[$id])) { $this->Error('The XObject Template \''.$id.'\' doesn\'t exist!'); } if ($this->inxobj) { if ($id == $this->xobjid) { // close current template $this->endTemplate(); } else { // use the template as resource for the template currently opened $this->xobjects[$this->xobjid]['xobjects'][$id] = $this->xobjects[$id]; } } // set default values if ($x === '') { $x = $this->x; } if ($y === '') { $y = $this->y; } $ow = $this->xobjects[$id]['w']; $oh = $this->xobjects[$id]['h']; // calculate image width and height on document if (($w <= 0) AND ($h <= 0)) { $w = $ow; $h = $oh; } elseif ($w <= 0) { $w = $h * $ow / $oh; } elseif ($h <= 0) { $h = $w * $oh / $ow; } // fit the image on available space $this->fitBlock($w, $h, $x, $y, $fitonpage); // set page alignment $rb_y = $y + $h; // set alignment if ($this->rtl) { if ($palign == 'L') { $xt = $this->lMargin; } elseif ($palign == 'C') { $xt = ($this->w + $this->lMargin - $this->rMargin - $w) / 2; } elseif ($palign == 'R') { $xt = $this->w - $this->rMargin - $w; } else { $xt = $x - $w; } $rb_x = $xt; } else { if ($palign == 'L') { $xt = $this->lMargin; } elseif ($palign == 'C') { $xt = ($this->w + $this->lMargin - $this->rMargin - $w) / 2; } elseif ($palign == 'R') { $xt = $this->w - $this->rMargin - $w; } else { $xt = $x; } $rb_x = $xt + $w; } // print XObject Template + Transformation matrix $this->StartTransform(); // translate and scale $sx = ($w / $this->xobjects[$id]['w']); $sy = ($h / $this->xobjects[$id]['h']); $tm = array(); $tm[0] = $sx; $tm[1] = 0; $tm[2] = 0; $tm[3] = $sy; $tm[4] = $xt * $this->k; $tm[5] = ($this->h - $h - $y) * $this->k; $this->Transform($tm); // set object $this->_out('/'.$id.' Do'); $this->StopTransform(); // add annotations if (!empty($this->xobjects[$id]['annotations'])) { foreach ($this->xobjects[$id]['annotations'] as $annot) { // transform original coordinates $coordlt = $this->getTransformationMatrixProduct($tm, array(1, 0, 0, 1, ($annot['x'] * $this->k), (-$annot['y'] * $this->k))); $ax = ($coordlt[4] / $this->k); $ay = ($this->h - $h - ($coordlt[5] / $this->k)); $coordrb = $this->getTransformationMatrixProduct($tm, array(1, 0, 0, 1, (($annot['x'] + $annot['w']) * $this->k), ((-$annot['y'] - $annot['h']) * $this->k))); $aw = ($coordrb[4] / $this->k) - $ax; $ah = ($this->h - $h - ($coordrb[5] / $this->k)) - $ay; $this->Annotation($ax, $ay, $aw, $ah, $annot['text'], $annot['opt'], $annot['spaces']); } } // set pointer to align the next text/objects switch($align) { case 'T': { $this->y = $y; $this->x = $rb_x; break; } case 'M': { $this->y = $y + round($h/2); $this->x = $rb_x; break; } case 'B': { $this->y = $rb_y; $this->x = $rb_x; break; } case 'N': { $this->SetY($rb_y); break; } default:{ break; } } } // -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.- // SVG METHODS // -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.- /** * Embedd a Scalable Vector Graphics (SVG) image. * NOTE: SVG standard is not yet fully implemented, use the setRasterizeVectorImages() method to enable/disable rasterization of vector images using ImageMagick library. * @param string $file Name of the SVG file. * @param float $x Abscissa of the upper-left corner. * @param float $y Ordinate of the upper-left corner. * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated. * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated. * @param mixed $link URL or identifier returned by AddLink(). * @param string $align Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul> If the alignment is an empty string, then the pointer will be restored on the starting SVG position. * @param string $palign Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul> * @param mixed $border Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0))) * @param boolean $fitonpage if true the image is resized to not exceed page dimensions. * @author Nicola Asuni * @since 5.0.000 (2010-05-02) * @access public */ public function ImageSVG($file, $x='', $y='', $w=0, $h=0, $link='', $align='', $palign='', $border=0, $fitonpage=false) { if ($this->rasterize_vector_images AND ($w > 0) AND ($h > 0)) { // convert SVG to raster image using GD or ImageMagick libraries return $this->Image($file, $x, $y, $w, $h, 'SVG', $link, $align, true, 300, $palign, false, false, $border, false, false, false); } $this->svgdir = dirname($file); $svgdata = file_get_contents($file); if ($svgdata === false) { $this->Error('SVG file not found: '.$file); } if ($x === '') { $x = $this->x; } if ($y === '') { $y = $this->y; } $k = $this->k; $ox = 0; $oy = 0; $ow = $w; $oh = $h; $aspect_ratio_align = 'xMidYMid'; $aspect_ratio_ms = 'meet'; $regs = array(); // get original image width and height preg_match('/<svg([^\>]*)>/si', $svgdata, $regs); if (isset($regs[1]) AND !empty($regs[1])) { $tmp = array(); if (preg_match('/[\s]+x[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) { $ox = $this->getHTMLUnitToUnits($tmp[1], 0, $this->svgunit, false); } $tmp = array(); if (preg_match('/[\s]+y[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) { $oy = $this->getHTMLUnitToUnits($tmp[1], 0, $this->svgunit, false); } $tmp = array(); if (preg_match('/[\s]+width[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) { $ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false); } $tmp = array(); if (preg_match('/[\s]+height[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) { $oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false); } $tmp = array(); $view_box = array(); if (preg_match('/[\s]+viewBox[\s]*=[\s]*"[\s]*([0-9\.\-]+)[\s]+([0-9\.\-]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]*"/si', $regs[1], $tmp)) { if (count($tmp) == 5) { array_shift($tmp); foreach ($tmp as $key => $val) { $view_box[$key] = $this->getHTMLUnitToUnits($val, 0, $this->svgunit, false); } $ox = $view_box[0]; $oy = $view_box[1]; } // get aspect ratio $tmp = array(); if (preg_match('/[\s]+preserveAspectRatio[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) { $aspect_ratio = preg_split('/[\s]+/si', $tmp[1]); switch (count($aspect_ratio)) { case 3: { $aspect_ratio_align = $aspect_ratio[1]; $aspect_ratio_ms = $aspect_ratio[2]; break; } case 2: { $aspect_ratio_align = $aspect_ratio[0]; $aspect_ratio_ms = $aspect_ratio[1]; break; } case 1: { $aspect_ratio_align = $aspect_ratio[0]; $aspect_ratio_ms = 'meet'; break; } } } } } // calculate image width and height on document if (($w <= 0) AND ($h <= 0)) { // convert image size to document unit $w = $ow; $h = $oh; } elseif ($w <= 0) { $w = $h * $ow / $oh; } elseif ($h <= 0) { $h = $w * $oh / $ow; } // fit the image on available space $this->fitBlock($w, $h, $x, $y, $fitonpage); if ($this->rasterize_vector_images) { // convert SVG to raster image using GD or ImageMagick libraries return $this->Image($file, $x, $y, $w, $h, 'SVG', $link, $align, true, 300, $palign, false, false, $border, false, false, false); } // set alignment $this->img_rb_y = $y + $h; // set alignment if ($this->rtl) { if ($palign == 'L') { $ximg = $this->lMargin; } elseif ($palign == 'C') { $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2; } elseif ($palign == 'R') { $ximg = $this->w - $this->rMargin - $w; } else { $ximg = $x - $w; } $this->img_rb_x = $ximg; } else { if ($palign == 'L') { $ximg = $this->lMargin; } elseif ($palign == 'C') { $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2; } elseif ($palign == 'R') { $ximg = $this->w - $this->rMargin - $w; } else { $ximg = $x; } $this->img_rb_x = $ximg + $w; } // store current graphic vars $gvars = $this->getGraphicVars(); // store SVG position and scale factors $svgoffset_x = ($ximg - $ox) * $this->k; $svgoffset_y = -($y - $oy) * $this->k; if (isset($view_box[2]) AND ($view_box[2] > 0) AND ($view_box[3] > 0)) { $ow = $view_box[2]; $oh = $view_box[3]; } $svgscale_x = $w / $ow; $svgscale_y = $h / $oh; // scaling and alignment if ($aspect_ratio_align != 'none') { // store current scaling values $svgscale_old_x = $svgscale_x; $svgscale_old_y = $svgscale_y; // force uniform scaling if ($aspect_ratio_ms == 'slice') { // the entire viewport is covered by the viewBox if ($svgscale_x > $svgscale_y) { $svgscale_y = $svgscale_x; } elseif ($svgscale_x < $svgscale_y) { $svgscale_x = $svgscale_y; } } else { // meet // the entire viewBox is visible within the viewport if ($svgscale_x < $svgscale_y) { $svgscale_y = $svgscale_x; } elseif ($svgscale_x > $svgscale_y) { $svgscale_x = $svgscale_y; } } // correct X alignment switch (substr($aspect_ratio_align, 1, 3)) { case 'Min': { // do nothing break; } case 'Max': { $svgoffset_x += (($w * $this->k) - ($ow * $this->k * $svgscale_x)); break; } default: case 'Mid': { $svgoffset_x += ((($w * $this->k) - ($ow * $this->k * $svgscale_x)) / 2); break; } } // correct Y alignment switch (substr($aspect_ratio_align, 5)) { case 'Min': { // do nothing break; } case 'Max': { $svgoffset_y -= (($h * $this->k) - ($oh * $this->k * $svgscale_y)); break; } default: case 'Mid': { $svgoffset_y -= ((($h * $this->k) - ($oh * $this->k * $svgscale_y)) / 2); break; } } } // store current page break mode $page_break_mode = $this->AutoPageBreak; $page_break_margin = $this->getBreakMargin(); $cMargin = $this->cMargin; $this->cMargin = 0; $this->SetAutoPageBreak(false); // save the current graphic state $this->_out('q'.$this->epsmarker); // set initial clipping mask $this->Rect($x, $y, $w, $h, 'CNZ', array(), array()); // scale and translate $e = $ox * $this->k * (1 - $svgscale_x); $f = ($this->h - $oy) * $this->k * (1 - $svgscale_y); $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', $svgscale_x, 0, 0, $svgscale_y, $e + $svgoffset_x, $f + $svgoffset_y)); // creates a new XML parser to be used by the other XML functions $this->parser = xml_parser_create('UTF-8'); // the following function allows to use parser inside object xml_set_object($this->parser, $this); // disable case-folding for this XML parser xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); // sets the element handler functions for the XML parser xml_set_element_handler($this->parser, 'startSVGElementHandler', 'endSVGElementHandler'); // sets the character data handler function for the XML parser xml_set_character_data_handler($this->parser, 'segSVGContentHandler'); // start parsing an XML document if(!xml_parse($this->parser, $svgdata)) { $error_message = sprintf("SVG Error: %s at line %d", xml_error_string(xml_get_error_code($this->parser)), xml_get_current_line_number($this->parser)); $this->Error($error_message); } // free this XML parser xml_parser_free($this->parser); // restore previous graphic state $this->_out($this->epsmarker.'Q'); // restore graphic vars $this->setGraphicVars($gvars); $this->lasth = $gvars['lasth']; if (!empty($border)) { $bx = $this->x; $by = $this->y; $this->x = $ximg; if ($this->rtl) { $this->x += $w; } $this->y = $y; $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true); $this->x = $bx; $this->y = $by; } if ($link) { $this->Link($ximg, $y, $w, $h, $link, 0); } // set pointer to align the next text/objects switch($align) { case 'T':{ $this->y = $y; $this->x = $this->img_rb_x; break; } case 'M':{ $this->y = $y + round($h/2); $this->x = $this->img_rb_x; break; } case 'B':{ $this->y = $this->img_rb_y; $this->x = $this->img_rb_x; break; } case 'N':{ $this->SetY($this->img_rb_y); break; } default:{ // restore pointer to starting position $this->x = $gvars['x']; $this->y = $gvars['y']; $this->page = $gvars['page']; $this->current_column = $gvars['current_column']; $this->tMargin = $gvars['tMargin']; $this->bMargin = $gvars['bMargin']; $this->w = $gvars['w']; $this->h = $gvars['h']; $this->wPt = $gvars['wPt']; $this->hPt = $gvars['hPt']; $this->fwPt = $gvars['fwPt']; $this->fhPt = $gvars['fhPt']; break; } } $this->endlinex = $this->img_rb_x; // restore page break $this->SetAutoPageBreak($page_break_mode, $page_break_margin); $this->cMargin = $cMargin; } /** * Get the tranformation matrix from SVG transform attribute * @param string transformation * @return array of transformations * @author Nicola Asuni * @since 5.0.000 (2010-05-02) * @access protected */ protected function getSVGTransformMatrix($attribute) { // identity matrix $tm = array(1, 0, 0, 1, 0, 0); $transform = array(); if (preg_match_all('/(matrix|translate|scale|rotate|skewX|skewY)[\s]*\(([^\)]+)\)/si', $attribute, $transform, PREG_SET_ORDER) > 0) { foreach ($transform as $key => $data) { if (!empty($data[2])) { $a = 1; $b = 0; $c = 0; $d = 1; $e = 0; $f = 0; $regs = array(); switch ($data[1]) { case 'matrix': { if (preg_match('/([a-z0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)/si', $data[2], $regs)) { $a = $regs[1]; $b = $regs[2]; $c = $regs[3]; $d = $regs[4]; $e = $regs[5]; $f = $regs[6]; } break; } case 'translate': { if (preg_match('/([a-z0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)/si', $data[2], $regs)) { $e = $regs[1]; $f = $regs[2]; } elseif (preg_match('/([a-z0-9\-\.]+)/si', $data[2], $regs)) { $e = $regs[1]; } break; } case 'scale': { if (preg_match('/([a-z0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)/si', $data[2], $regs)) { $a = $regs[1]; $d = $regs[2]; } elseif (preg_match('/([a-z0-9\-\.]+)/si', $data[2], $regs)) { $a = $regs[1]; $d = $a; } break; } case 'rotate': { if (preg_match('/([0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)/si', $data[2], $regs)) { $ang = deg2rad($regs[1]); $x = $regs[2]; $y = $regs[3]; $a = cos($ang); $b = sin($ang); $c = -$b; $d = $a; $e = ($x * (1 - $a)) - ($y * $c); $f = ($y * (1 - $d)) - ($x * $b); } elseif (preg_match('/([0-9\-\.]+)/si', $data[2], $regs)) { $ang = deg2rad($regs[1]); $a = cos($ang); $b = sin($ang); $c = -$b; $d = $a; $e = 0; $f = 0; } break; } case 'skewX': { if (preg_match('/([0-9\-\.]+)/si', $data[2], $regs)) { $c = tan(deg2rad($regs[1])); } break; } case 'skewY': { if (preg_match('/([0-9\-\.]+)/si', $data[2], $regs)) { $b = tan(deg2rad($regs[1])); } break; } } $tm = $this->getTransformationMatrixProduct($tm, array($a, $b, $c, $d, $e, $f)); } } } return $tm; } /** * Get the product of two SVG tranformation matrices * @param array $ta first SVG tranformation matrix * @param array $tb second SVG tranformation matrix * @return transformation array * @author Nicola Asuni * @since 5.0.000 (2010-05-02) * @access protected */ protected function getTransformationMatrixProduct($ta, $tb) { $tm = array(); $tm[0] = ($ta[0] * $tb[0]) + ($ta[2] * $tb[1]); $tm[1] = ($ta[1] * $tb[0]) + ($ta[3] * $tb[1]); $tm[2] = ($ta[0] * $tb[2]) + ($ta[2] * $tb[3]); $tm[3] = ($ta[1] * $tb[2]) + ($ta[3] * $tb[3]); $tm[4] = ($ta[0] * $tb[4]) + ($ta[2] * $tb[5]) + $ta[4]; $tm[5] = ($ta[1] * $tb[4]) + ($ta[3] * $tb[5]) + $ta[5]; return $tm; } /** * Convert SVG transformation matrix to PDF. * @param array $tm original SVG transformation matrix * @return array transformation matrix * @access protected * @since 5.0.000 (2010-05-02) */ protected function convertSVGtMatrix($tm) { $a = $tm[0]; $b = -$tm[1]; $c = -$tm[2]; $d = $tm[3]; $e = $this->getHTMLUnitToUnits($tm[4], 1, $this->svgunit, false) * $this->k; $f = -$this->getHTMLUnitToUnits($tm[5], 1, $this->svgunit, false) * $this->k; $x = 0; $y = $this->h * $this->k; $e = ($x * (1 - $a)) - ($y * $c) + $e; $f = ($y * (1 - $d)) - ($x * $b) + $f; return array($a, $b, $c, $d, $e, $f); } /** * Apply SVG graphic transformation matrix. * @param array $tm original SVG transformation matrix * @access protected * @since 5.0.000 (2010-05-02) */ protected function SVGTransform($tm) { $this->Transform($this->convertSVGtMatrix($tm)); } /** * Apply the requested SVG styles (*** TO BE COMPLETED ***) * @param array $svgstyle array of SVG styles to apply * @param array $prevsvgstyle array of previous SVG style * @param int $x X origin of the bounding box * @param int $y Y origin of the bounding box * @param int $w width of the bounding box * @param int $h height of the bounding box * @param string $clip_function clip function * @param array $clip_params array of parameters for clipping function * @return object style * @author Nicola Asuni * @since 5.0.000 (2010-05-02) * @access protected */ protected function setSVGStyles($svgstyle, $prevsvgstyle, $x=0, $y=0, $w=1, $h=1, $clip_function='', $clip_params=array()) { $objstyle = ''; if(!isset($svgstyle['opacity'])) { return $objstyle; } // clip-path $regs = array(); if (preg_match('/url\([\s]*\#([^\)]*)\)/si', $svgstyle['clip-path'], $regs)) { $clip_path = $this->svgclippaths[$regs[1]]; foreach ($clip_path as $cp) { $this->startSVGElementHandler('clip-path', $cp['name'], $cp['attribs'], $cp['tm']); } } // opacity if ($svgstyle['opacity'] != 1) { $this->SetAlpha($svgstyle['opacity']); } // color $fill_color = $this->convertHTMLColorToDec($svgstyle['color']); $this->SetFillColorArray($fill_color); // text color $text_color = $this->convertHTMLColorToDec($svgstyle['text-color']); $this->SetTextColorArray($text_color); // clip if (preg_match('/rect\(([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)\)/si', $svgstyle['clip'], $regs)) { $top = (isset($regs[1])?$this->getHTMLUnitToUnits($regs[1], 0, $this->svgunit, false):0); $right = (isset($regs[2])?$this->getHTMLUnitToUnits($regs[2], 0, $this->svgunit, false):0); $bottom = (isset($regs[3])?$this->getHTMLUnitToUnits($regs[3], 0, $this->svgunit, false):0); $left = (isset($regs[4])?$this->getHTMLUnitToUnits($regs[4], 0, $this->svgunit, false):0); $cx = $x + $left; $cy = $y + $top; $cw = $w - $left - $right; $ch = $h - $top - $bottom; if ($svgstyle['clip-rule'] == 'evenodd') { $clip_rule = 'CNZ'; } else { $clip_rule = 'CEO'; } $this->Rect($cx, $cy, $cw, $ch, $clip_rule, array(), array()); } // fill $regs = array(); if (preg_match('/url\([\s]*\#([^\)]*)\)/si', $svgstyle['fill'], $regs)) { // gradient $gradient = $this->svggradients[$regs[1]]; if (isset($gradient['xref'])) { // reference to another gradient definition $newgradient = $this->svggradients[$gradient['xref']]; $newgradient['coords'] = $gradient['coords']; $newgradient['mode'] = $gradient['mode']; $newgradient['gradientUnits'] = $gradient['gradientUnits']; if (isset($gradient['gradientTransform'])) { $newgradient['gradientTransform'] = $gradient['gradientTransform']; } $gradient = $newgradient; } //save current Graphic State $this->_out('q'); //set clipping area if (!empty($clip_function) AND method_exists($this, $clip_function)) { $bbox = call_user_func_array(array($this, $clip_function), $clip_params); if (is_array($bbox) AND (count($bbox) == 4)) { list($x, $y, $w, $h) = $bbox; } } if ($gradient['mode'] == 'measure') { if (isset($gradient['gradientTransform']) AND !empty($gradient['gradientTransform'])) { $gtm = $gradient['gradientTransform']; // apply transformation matrix $xa = ($gtm[0] * $gradient['coords'][0]) + ($gtm[2] * $gradient['coords'][1]) + $gtm[4]; $ya = ($gtm[1] * $gradient['coords'][0]) + ($gtm[3] * $gradient['coords'][1]) + $gtm[5]; $xb = ($gtm[0] * $gradient['coords'][2]) + ($gtm[2] * $gradient['coords'][3]) + $gtm[4]; $yb = ($gtm[1] * $gradient['coords'][2]) + ($gtm[3] * $gradient['coords'][3]) + $gtm[5]; if (isset($gradient['coords'][4])) { $gradient['coords'][4] = sqrt(pow(($gtm[0] * $gradient['coords'][4]), 2) + pow(($gtm[1] * $gradient['coords'][4]), 2)); } $gradient['coords'][0] = $xa; $gradient['coords'][1] = $ya; $gradient['coords'][2] = $xb; $gradient['coords'][3] = $yb; } // convert SVG coordinates to user units $gradient['coords'][0] = $this->getHTMLUnitToUnits($gradient['coords'][0], 0, $this->svgunit, false); $gradient['coords'][1] = $this->getHTMLUnitToUnits($gradient['coords'][1], 0, $this->svgunit, false); $gradient['coords'][2] = $this->getHTMLUnitToUnits($gradient['coords'][2], 0, $this->svgunit, false); $gradient['coords'][3] = $this->getHTMLUnitToUnits($gradient['coords'][3], 0, $this->svgunit, false); if (isset($gradient['coords'][4])) { $gradient['coords'][4] = $this->getHTMLUnitToUnits($gradient['coords'][4], 0, $this->svgunit, false); } // shift units if ($gradient['gradientUnits'] == 'objectBoundingBox') { // convert to SVG coordinate system $gradient['coords'][0] += $x; $gradient['coords'][1] += $y; $gradient['coords'][2] += $x; $gradient['coords'][3] += $y; } // calculate percentages $gradient['coords'][0] = ($gradient['coords'][0] - $x) / $w; $gradient['coords'][1] = ($gradient['coords'][1] - $y) / $h; $gradient['coords'][2] = ($gradient['coords'][2] - $x) / $w; $gradient['coords'][3] = ($gradient['coords'][3] - $y) / $h; if (isset($gradient['coords'][4])) { $gradient['coords'][4] /= $w; } // fix values foreach($gradient['coords'] as $key => $val) { if ($val < 0) { $gradient['coords'][$key] = 0; } elseif ($val > 1) { $gradient['coords'][$key] = 1; } } if (($gradient['type'] == 2) AND ($gradient['coords'][0] == $gradient['coords'][2]) AND ($gradient['coords'][1] == $gradient['coords'][3])) { // single color (no shading) $gradient['coords'][0] = 1; $gradient['coords'][1] = 0; $gradient['coords'][2] = 0.999; $gradient['coords'][3] = 0; } } // swap Y coordinates $tmp = $gradient['coords'][1]; $gradient['coords'][1] = $gradient['coords'][3]; $gradient['coords'][3] = $tmp; // set transformation map for gradient if (($gradient['type'] == 3) AND ($gradient['mode'] == 'measure')) { // gradient is always circular $cy = $this->h - $y - ($gradient['coords'][1] * ($w + $h)); $this->_out(sprintf('%.3F 0 0 %.3F %.3F %.3F cm', $w*$this->k, $w*$this->k, $x*$this->k, $cy*$this->k)); } else { $this->_out(sprintf('%.3F 0 0 %.3F %.3F %.3F cm', $w*$this->k, $h*$this->k, $x*$this->k, ($this->h-($y+$h))*$this->k)); } if (count($gradient['stops']) > 1) { $this->Gradient($gradient['type'], $gradient['coords'], $gradient['stops'], array(), false); } } elseif ($svgstyle['fill'] != 'none') { $fill_color = $this->convertHTMLColorToDec($svgstyle['fill']); if ($svgstyle['fill-opacity'] != 1) { $this->SetAlpha($svgstyle['fill-opacity']); } $this->SetFillColorArray($fill_color); if ($svgstyle['fill-rule'] == 'evenodd') { $objstyle .= 'F*'; } else { $objstyle .= 'F'; } } // stroke if ($svgstyle['stroke'] != 'none') { $stroke_style = array( 'color' => $this->convertHTMLColorToDec($svgstyle['stroke']), 'width' => $this->getHTMLUnitToUnits($svgstyle['stroke-width'], 0, $this->svgunit, false), 'cap' => $svgstyle['stroke-linecap'], 'join' => $svgstyle['stroke-linejoin'] ); if (isset($svgstyle['stroke-dasharray']) AND !empty($svgstyle['stroke-dasharray']) AND ($svgstyle['stroke-dasharray'] != 'none')) { $stroke_style['dash'] = $svgstyle['stroke-dasharray']; } $this->SetLineStyle($stroke_style); $objstyle .= 'D'; } // font $regs = array(); if (!empty($svgstyle['font'])) { if (preg_match('/font-family[\s]*:[\s]*([^\;\"]*)/si', $svgstyle['font'], $regs)) { $font_family = $this->getFontFamilyName($regs[1]); } else { $font_family = $svgstyle['font-family']; } if (preg_match('/font-size[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) { $font_size = trim($regs[1]); } else { $font_size = $svgstyle['font-size']; } if (preg_match('/font-style[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) { $font_style = trim($regs[1]); } else { $font_style = $svgstyle['font-style']; } if (preg_match('/font-weight[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) { $font_weight = trim($regs[1]); } else { $font_weight = $svgstyle['font-weight']; } } else { $font_family = $this->getFontFamilyName($svgstyle['font-family']); $font_size = $svgstyle['font-size']; $font_style = $svgstyle['font-style']; $font_weight = $svgstyle['font-weight']; } $font_size = $this->getHTMLUnitToUnits($font_size, $prevsvgstyle['font-size'], $this->svgunit, false) * $this->k; switch ($font_style) { case 'italic': { $font_style = 'I'; break; } case 'oblique': { $font_style = 'I'; break; } default: case 'normal': { $font_style = ''; break; } } switch ($font_weight) { case 'bold': case 'bolder': { $font_style .= 'B'; break; } } switch ($svgstyle['text-decoration']) { case 'underline': { $font_style .= 'U'; break; } case 'overline': { $font_style .= 'O'; break; } case 'line-through': { $font_style .= 'D'; break; } default: case 'none': { break; } } $this->SetFont($font_family, $font_style, $font_size); return $objstyle; } /** * Draws an SVG path * @param string $d attribute d of the path SVG element * @param string $style Style of rendering. Possible values are: * <ul> * <li>D or empty string: Draw (default).</li> * <li>F: Fill.</li> * <li>F*: Fill using the even-odd rule to determine which regions lie inside the clipping path.</li> * <li>DF or FD: Draw and fill.</li> * <li>DF* or FD*: Draw and fill using the even-odd rule to determine which regions lie inside the clipping path.</li> * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li> * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li> * </ul> * @return array of container box measures (x, y, w, h) * @author Nicola Asuni * @since 5.0.000 (2010-05-02) * @access protected */ protected function SVGPath($d, $style='') { // set fill/stroke style $op = $this->getPathPaintOperator($style, ''); if (empty($op)) { return; } $paths = array(); $d = str_replace('-', ' -', $d); $d = str_replace('+', ' +', $d); preg_match_all('/([a-zA-Z])[\s]*([^a-zA-Z\"]*)/si', $d, $paths, PREG_SET_ORDER); $x = 0; $y = 0; $x1 = 0; $y1 = 0; $x2 = 0; $y2 = 0; $xmin = 2147483647; $xmax = 0; $ymin = 2147483647; $ymax = 0; $relcoord = false; // draw curve pieces foreach ($paths as $key => $val) { // get curve type $cmd = trim($val[1]); if (strtolower($cmd) == $cmd) { // use relative coordinated instead of absolute $relcoord = true; $xoffset = $x; $yoffset = $y; } else { $relcoord = false; $xoffset = 0; $yoffset = 0; } $params = array(); if (isset($val[2])) { // get curve parameters $rawparams = preg_split('/([\,\s]+)/si', trim($val[2])); $params = array(); foreach ($rawparams as $ck => $cp) { $params[$ck] = $this->getHTMLUnitToUnits($cp, 0, $this->svgunit, false); } } switch (strtoupper($cmd)) { case 'M': { // moveto foreach ($params as $ck => $cp) { if (($ck % 2) == 0) { $x = $cp + $xoffset; } else { $y = $cp + $yoffset; if ($ck == 1) { $this->_outPoint($x, $y); } else { $this->_outLine($x, $y); } $xmin = min($xmin, $x); $ymin = min($ymin, $y); $xmax = max($xmax, $x); $ymax = max($ymax, $y); if ($relcoord) { $xoffset = $x; $yoffset = $y; } } } break; } case 'L': { // lineto foreach ($params as $ck => $cp) { if (($ck % 2) == 0) { $x = $cp + $xoffset; } else { $y = $cp + $yoffset; $this->_outLine($x, $y); $xmin = min($xmin, $x); $ymin = min($ymin, $y); $xmax = max($xmax, $x); $ymax = max($ymax, $y); if ($relcoord) { $xoffset = $x; $yoffset = $y; } } } break; } case 'H': { // horizontal lineto foreach ($params as $ck => $cp) { $x = $cp + $xoffset; $this->_outLine($x, $y); $xmin = min($xmin, $x); $xmax = max($xmax, $x); if ($relcoord) { $xoffset = $x; } } break; } case 'V': { // vertical lineto foreach ($params as $ck => $cp) { $y = $cp + $yoffset; $this->_outLine($x, $y); $ymin = min($ymin, $y); $ymax = max($ymax, $y); if ($relcoord) { $yoffset = $y; } } break; } case 'C': { // curveto foreach ($params as $ck => $cp) { $params[$ck] = $cp; if ((($ck + 1) % 6) == 0) { $x1 = $params[($ck - 5)] + $xoffset; $y1 = $params[($ck - 4)] + $yoffset; $x2 = $params[($ck - 3)] + $xoffset; $y2 = $params[($ck - 2)] + $yoffset; $x = $params[($ck - 1)] + $xoffset; $y = $params[($ck)] + $yoffset; $this->_outCurve($x1, $y1, $x2, $y2, $x, $y); $xmin = min($xmin, $x, $x1, $x2); $ymin = min($ymin, $y, $y1, $y2); $xmax = max($xmax, $x, $x1, $x2); $ymax = max($ymax, $y, $y1, $y2); if ($relcoord) { $xoffset = $x; $yoffset = $y; } } } break; } case 'S': { // shorthand/smooth curveto foreach ($params as $ck => $cp) { $params[$ck] = $cp; if ((($ck + 1) % 4) == 0) { if (($key > 0) AND ((strtoupper($paths[($key - 1)][1]) == 'C') OR (strtoupper($paths[($key - 1)][1]) == 'S'))) { $x1 = (2 * $x) - $x2; $y1 = (2 * $y) - $y2; } else { $x1 = $x; $y1 = $y; } $x2 = $params[($ck - 3)] + $xoffset; $y2 = $params[($ck - 2)] + $yoffset; $x = $params[($ck - 1)] + $xoffset; $y = $params[($ck)] + $yoffset; $this->_outCurve($x1, $y1, $x2, $y2, $x, $y); $xmin = min($xmin, $x, $x1, $x2); $ymin = min($ymin, $y, $y1, $y2); $xmax = max($xmax, $x, $x1, $x2); $ymax = max($ymax, $y, $y1, $y2); if ($relcoord) { $xoffset = $x; $yoffset = $y; } } } break; } case 'Q': { // quadratic Bézier curveto foreach ($params as $ck => $cp) { $params[$ck] = $cp; if ((($ck + 1) % 4) == 0) { // convert quadratic points to cubic points $x1 = $params[($ck - 3)] + $xoffset; $y1 = $params[($ck - 2)] + $yoffset; $xa = ($x + (2 * $x1)) / 3; $ya = ($y + (2 * $y1)) / 3; $x = $params[($ck - 1)] + $xoffset; $y = $params[($ck)] + $yoffset; $xb = ($x + (2 * $x1)) / 3; $yb = ($y + (2 * $y1)) / 3; $this->_outCurve($xa, $ya, $xb, $yb, $x, $y); $xmin = min($xmin, $x, $xa, $xb); $ymin = min($ymin, $y, $ya, $yb); $xmax = max($xmax, $x, $xa, $xb); $ymax = max($ymax, $y, $ya, $yb); if ($relcoord) { $xoffset = $x; $yoffset = $y; } } } break; } case 'T': { // shorthand/smooth quadratic Bézier curveto foreach ($params as $ck => $cp) { $params[$ck] = $cp; if (($ck % 2) != 0) { if (($key > 0) AND ((strtoupper($paths[($key - 1)][1]) == 'Q') OR (strtoupper($paths[($key - 1)][1]) == 'T'))) { $x1 = (2 * $x) - $x1; $y1 = (2 * $y) - $y1; } else { $x1 = $x; $y1 = $y; } // convert quadratic points to cubic points $xa = ($x + (2 * $x1)) / 3; $ya = ($y + (2 * $y1)) / 3; $x = $params[($ck - 1)] + $xoffset; $y = $params[($ck)] + $yoffset; $xb = ($x + (2 * $x1)) / 3; $yb = ($y + (2 * $y1)) / 3; $this->_outCurve($xa, $ya, $xb, $yb, $x, $y); $xmin = min($xmin, $x, $x1, $x2); $ymin = min($ymin, $y, $y1, $y2); $xmax = max($xmax, $x, $x1, $x2); $ymax = max($ymax, $y, $y1, $y2); if ($relcoord) { $xoffset = $x; $yoffset = $y; } } } break; } case 'A': { // elliptical arc foreach ($params as $ck => $cp) { $params[$ck] = $cp; if ((($ck + 1) % 7) == 0) { $x0 = $x; $y0 = $y; $rx = abs($params[($ck - 6)]); $ry = abs($params[($ck - 5)]); $ang = -$rawparams[($ck - 4)]; $angle = deg2rad($ang); $fa = $rawparams[($ck - 3)]; // large-arc-flag $fs = $rawparams[($ck - 2)]; // sweep-flag $x = $params[($ck - 1)] + $xoffset; $y = $params[$ck] + $yoffset; $cos_ang = cos($angle); $sin_ang = sin($angle); $a = ($x0 - $x) / 2; $b = ($y0 - $y) / 2; $xa = ($a * $cos_ang) - ($b * $sin_ang); $ya = ($a * $sin_ang) + ($b * $cos_ang); $rx2 = $rx * $rx; $ry2 = $ry * $ry; $xa2 = $xa * $xa; $ya2 = $ya * $ya; $delta = ($xa2 / $rx2) + ($ya2 / $ry2); if ($delta > 1) { $rx *= sqrt($delta); $ry *= sqrt($delta); $rx2 = $rx * $rx; $ry2 = $ry * $ry; } $numerator = (($rx2 * $ry2) - ($rx2 * $ya2) - ($ry2 * $xa2)); if ($numerator < 0) { $root = 0; } else { $root = sqrt($numerator / (($rx2 * $ya2) + ($ry2 * $xa2))); } if ($fa == $fs) { $root *= -1; } $cax = $root * (($rx * $ya) / $ry); $cay = -$root * (($ry * $xa) / $rx); // coordinates of ellipse center $cx = ($cax * $cos_ang) - ($cay * $sin_ang) + (($x0 + $x) / 2); $cy = ($cax * $sin_ang) + ($cay * $cos_ang) + (($y0 + $y) / 2); // get angles $angs = $this->getVectorsAngle(1, 0, (($xa - $cax) / $rx), (($cay - $ya) / $ry)); $dang = $this->getVectorsAngle((($xa - $cax) / $rx), (($ya - $cay) / $ry), ((-$xa - $cax) / $rx), ((-$ya - $cay) / $ry)); if (($fs == 0) AND ($dang > 0)) { $dang -= (2 * M_PI); } elseif (($fs == 1) AND ($dang < 0)) { $dang += (2 * M_PI); } $angf = $angs - $dang; if (($fs == 1) AND ($angs > $angf)) { $tmp = $angs; $angs = $angf; $angf = $tmp; } $angs = rad2deg($angs); $angf = rad2deg($angf); $pie = false; if ((isset($paths[($key + 1)][1])) AND (trim($paths[($key + 1)][1]) == 'z')) { $pie = true; } $this->_outellipticalarc($cx, $cy, $rx, $ry, $ang, $angs, $angf, $pie, 2); $this->_outPoint($x, $y); $xmin = min($xmin, $x); $ymin = min($ymin, $y); $xmax = max($xmax, $x); $ymax = max($ymax, $y); if ($relcoord) { $xoffset = $x; $yoffset = $y; } } } break; } case 'Z': { $this->_out('h'); break; } } } // end foreach if (!empty($op)) { $this->_out($op); } return array($xmin, $ymin, ($xmax - $xmin), ($ymax - $ymin)); } /** * Returns the angle in radiants between two vectors * @param int $x1 X coordiante of first vector point * @param int $y1 Y coordiante of first vector point * @param int $x2 X coordiante of second vector point * @param int $y2 Y coordiante of second vector point * @author Nicola Asuni * @since 5.0.000 (2010-05-04) * @access protected */ protected function getVectorsAngle($x1, $y1, $x2, $y2) { $dprod = ($x1 * $x2) + ($y1 * $y2); $dist1 = sqrt(($x1 * $x1) + ($y1 * $y1)); $dist2 = sqrt(($x2 * $x2) + ($y2 * $y2)); $angle = acos($dprod / ($dist1 * $dist2)); if (is_nan($angle)) { $angle = M_PI; } if ((($x1 * $y2) - ($x2 * $y1)) < 0) { $angle *= -1; } return $angle; } /** * Sets the opening SVG element handler function for the XML parser. (*** TO BE COMPLETED ***) * @param resource $parser The first parameter, parser, is a reference to the XML parser calling the handler. * @param string $name The second parameter, name, contains the name of the element for which this handler is called. If case-folding is in effect for this parser, the element name will be in uppercase letters. * @param array $attribs The third parameter, attribs, contains an associative array with the element's attributes (if any). The keys of this array are the attribute names, the values are the attribute values. Attribute names are case-folded on the same criteria as element names. Attribute values are not case-folded. The original order of the attributes can be retrieved by walking through attribs the normal way, using each(). The first key in the array was the first attribute, and so on. * @param array $ctm tranformation matrix for clipping mode (starting transformation matrix). * @author Nicola Asuni * @since 5.0.000 (2010-05-02) * @access protected */ protected function startSVGElementHandler($parser, $name, $attribs, $ctm=array()) { // check if we are in clip mode if ($this->svgclipmode) { $this->svgclippaths[$this->svgclipid][] = array('name' => $name, 'attribs' => $attribs, 'tm' => $this->svgcliptm[$this->svgclipid]); return; } if ($this->svgdefsmode AND !in_array($name, array('clipPath', 'linearGradient', 'radialGradient', 'stop'))) { if (!isset($attribs['id'])) { $attribs['id'] = 'DF_'.(count($this->svgdefs) + 1); } $this->svgdefs[$attribs['id']] = array('name' => $name, 'attribs' => $attribs); return; } $clipping = false; if ($parser == 'clip-path') { // set clipping mode $clipping = true; } // get styling properties $prev_svgstyle = $this->svgstyles[(count($this->svgstyles) - 1)]; // previous style $svgstyle = $this->svgstyles[0]; // set default style if (isset($attribs['style']) AND !$this->empty_string($attribs['style'])) { // fix style for regular expression $attribs['style'] = ';'.$attribs['style']; } foreach ($prev_svgstyle as $key => $val) { if (in_array($key, $this->svginheritprop)) { // inherit previous value $svgstyle[$key] = $val; } if (isset($attribs[$key]) AND !$this->empty_string($attribs[$key])) { // specific attribute settings if ($attribs[$key] == 'inherit') { $svgstyle[$key] = $val; } else { $svgstyle[$key] = $attribs[$key]; } } elseif (isset($attribs['style']) AND !$this->empty_string($attribs['style'])) { // CSS style syntax $attrval = array(); if (preg_match('/[;\"\s]{1}'.$key.'[\s]*:[\s]*([^;\"]*)/si', $attribs['style'], $attrval) AND isset($attrval[1])) { if ($attrval[1] == 'inherit') { $svgstyle[$key] = $val; } else { $svgstyle[$key] = $attrval[1]; } } } } // transformation matrix if (!empty($ctm)) { $tm = $ctm; } else { $tm = $this->svgstyles[(count($this->svgstyles) - 1)]['transfmatrix']; } if (isset($attribs['transform']) AND !empty($attribs['transform'])) { $tm = $this->getTransformationMatrixProduct($tm, $this->getSVGTransformMatrix($attribs['transform'])); } $svgstyle['transfmatrix'] = $tm; $invisible = false; if (($svgstyle['visibility'] == 'hidden') OR ($svgstyle['visibility'] == 'collapse') OR ($svgstyle['display'] == 'none')) { // the current graphics element is invisible (nothing is painted) $invisible = true; } // process tag switch($name) { case 'defs': { $this->svgdefsmod
__label__pos
0.974694
NCERT Solutions for Class 12th: Ch 3 Matrices Exercise 3.1 NCERT Solutions for Class 12th: Ch 3 Matrices Exercise 3.1 Math Page No: 64 Exercise 3.1 Find the value of the following: Question: 1 (i) The order of the matrix, (ii) The number of elements, (iii) Write the elements a13, a21, a33, a24, a23. Answer (i) In the given matrix, the number of rows is 3 and the number of columns is 4. Therefore, the order of the matrix is 3 × 4. (ii) Since the order of the matrix is 3 × 4, there are 3 × 4 = 12 elements in it. (iii) a13 = 19, a21 = 35, a33 = −5, a24 = 12, a23 = 5/2 2. If a matrix has 24 elements, what are the possible orders it can have? What, if it has 13 elements? Answer We know that if a matrix is of the order m × n, it has mn elements. Thus, to find all the possible orders of a matrix having 24 elements, we have to find all the ordered pairs of natural numbers whose product is 24. The ordered pairs are: (1, 24), (24, 1), (2, 12), (12, 2), (3, 8), (8, 3), (4, 6), and (6, 4) Hence, the possible orders of a matrix having 24 elements are: 1 × 24, 24 × 1, 2 × 12, 12 × 2, 3 × 8, 8 × 3, 4 × 6, and 6 × 4 (1, 13) and (13, 1) are the ordered pairs of natural numbers whose product is 13. Hence, the possible orders of a matrix having 13 elements are 1 × 13 and 13 × 1. 3. If a matrix has 18 elements, what are the possible orders it can have? What, if it has 5 elements? Answer We know that if a matrix is of the order m × n, it has mn elements. Thus, to find all the possible orders of a matrix having 18 elements, we have to find all the ordered pairs of natural numbers whose product is 18. The ordered pairs are: (1, 18), (18, 1), (2, 9), (9, 2), (3, 6,), and (6, 3) Hence, the possible orders of a matrix having 18 elements are: 1 × 18, 18 × 1, 2 × 9, 9 × 2, 3 × 6, and 6 × 3 (1, 5) and (5, 1) are the ordered pairs of natural numbers whose product is 5. Hence, the possible orders of a matrix having 5 elements are 1 × 5 and 5 × 1.  4. Construct a 2 × 2 matrix, A = [aij], whose elements are given by: Answer 5. Construct a 3 × 4 matrix, whose elements are given by: (i) aij = 1/2 |-3 + j| (ii) aij = 2i - j Answer (i) aij = 1/2 |-3 + j| a11 = 1/2|−3 × 1 + 1| = 1/2|−3 + 1| = 1 a12 = 1/2|−3 × 1 + 2| = 1/2|−3 + 2| = 1/2 a13 = 1/2|−3 × 1 + 3| = 1/2|−3 + 3| = 0 a14 = 1/2|−3 × 1 + 4| = 1/2|−3 + 4| = 1/2 a21 = 1/2|−3 × 2 + 1| = 1/2|−6 + 1| = 5/2 a22 = 1/2|−3 × 2 + 2| = 1/2|−6 + 2| = 2 a23 = 1/2|−3 × 2 + 3| = 1/2|−6 + 3| = 3/2 a24 = 1/2|−3 × 2 + 4| = 1/2|−6 + 4| = 1 a31 = 1/2|−3 × 3 + 1| = 1/2|−9 + 1| = 4 a32 = 1/2|−3 × 3 + 2| = 1/2|−9 + 2| = 7/2 a33 = 1/2|−3 × 3 + 3| = 1/2|−9 + 3| = 3 a34 = 1/2|−3 × 3 + 4| = 1/2|−9 + 4| = 5/2 (ii) aij = 2i - j a11 = 2 × 1 − 1 = 2 −1 = 1 a12 = 2 × 1 − 2 = 2 −2 = 0 a13 = 2 × 1 − 3 = 2 −3 = -1 a14 = 2 × 1 − 4 = 2 −4 = -2 a21 = 2 × 2 − 1 = 4 −1 = 3 a22 = 2 × 2 − 2 = 4 −2 = 2 a23 = 2 × 2 − 3 = 4 −3 = 1 a24 = 2 × 2 − 4 = 4 −4 = 0 a31 = 2 × 3 − 1 = 6 −1 = 5 a32 = 2 × 3 − 2 = 6 −2 = 4 a33 = 2 × 3 − 3 = 6 −3 = 3 a34 = 2 × 3 − 4 = 6 −4 = 2 6. Find the values of x, y and z from the following equations: Answer (i) As the given matrices are equal, their corresponding elements are also equal. Comparing the corresponding elements, we get: x = 1, y = 4, and z = 3 (ii) As the given matrices are equal, their corresponding elements are also equal. Comparing the corresponding elements, we get: x + y = 6, xy = 8, 5 + z = 5 Now, 5 + z = 5 ⇒ z = 0 we know that: (x − y)2 = (x + y)2 − 4xy ⇒ (x − y)2 = 36 − 32 = 4 ⇒ x − y = ±2 Now, when x − y = 2 and x + y = 6, we get x = 4 and y = 2 When x − y = − 2 and x + y = 6, we get x = 2 and y = 4 ∴ x = 4, y = 2, and z = 0 or x = 2, y = 4, and z = 0 (iii) As the two matrices are equal, their corresponding elements are also equal. Comparing the corresponding elements, we get: x + y + z = 9 ... (1) x + z = 5 ........ (2) y + z = 7 ........ (3) From (1) and (2), we have: y + 5 = 9 ⇒ y = 4 Then, from (3), we have: 4 + z = 7 ⇒ z = 3 ∴ x + z = 5 ⇒ x = 2 ∴ x = 2, y = 4 and z = 3. 7. Find the value of a, b, c and d from the equation: Answer As the two matrices are equal, their corresponding elements are also equal. Comparing the corresponding elements, we get: a − b = −1 ...... (1) 2a − b = 0 ...... (2) 2a + c = 5 ....... (3) 3c + d = 13 ..... (4) From (2), we have: b = 2a Then, from (1), we have: a − 2a = −1 ⇒ a = 1 ⇒ b = 2 Now, from (3), we have: 2 ×1 + c = 5 ⇒ c = 3 From (4) we have: 3 × 3 + d = 13 ⇒ 9 + d = 13 ⇒ d = 4 ∴ a = 1, b = 2, c = 3 and d = 4. Page No. 65 8. A = [aij]mxn is a square matrix, if (A) m < n  (B) m > n  (C) m = n  (D) None of these Answer The correct answer is C. It is known that a given matrix is said to be a square matrix if the number of rows is equal to the number of columns. Therefore, A =[aij]mxn is a square matrix, if m = n. 9. Which of the given values of x and y make the following pair of matrices equal (A) x = -1/3, y = 7 (B) Not possible to find (C) y = 7, x = -2/3 (D) x = -1/3, y = -2/3 Answer The correct answer is B. It is given that, Equating the corresponding elements, we get: 3x + 7 = 0 ⇒ x = -7/3 and 5 = y − 2 ⇒ y = 7 y + 1 = 8 ⇒ y = 7 and 2 − 3x = 4 ⇒ x = -2/3 We find that on comparing the corresponding elements of the two matrices, we get two different values of x, which is not possible. Hence, it is not possible to find the values of x and y for which the given matrices are equal. 10. The number of all possible matrices of order 3 × 3 with each entry 0 or 1 is: (A) 27 (B) 18  (C) 81  (D) 512  Answer The correct answer is D. The given matrix of the order 3 × 3 has 9 elements and each of these elements can be either 0 or 1. Now, each of the 9 elements can be filled in two possible ways. Therefore, by the multiplication principle, the required number of possible matrices is 29 = 512 Watch age fraud in sports in India Liked NCERT Solutions and Notes, Share this with your friends:: Facebook Comments 0 Comments © 2017 Study Rankers is a registered trademark.
__label__pos
1
Introduction LogZilla dashboards are designed to present data in an interactive and real-time manner. Central to these dashboards are widgets, the foundational elements that serve to display this data. Every widget has the capability to present real-time information, ensuring users have immediate access to the most up-to-date and pertinent data. The adaptability of LogZilla's widgets sets them apart. They offer a wide range of customization options, from adjusting visualizations to meet the needs of a specific audience to focusing on particular data subsets. Key features of the LogZilla dashboards include: • Multiple Custom Dashboards: Design various dashboards specifically tailored for individual tasks, departments, or goals. • Role-Based Permissions (RBAC): LogZilla integrates Role-Based Access Control (RBAC) to meticulously manage both data and user interface (UI) access: • Access to Data: RBAC governs which data sets a user or a group can access. For instance, in a widget showcasing top hosts, users will only visualize those hosts they have been granted permission to view. • Access to UI Components: Beyond just data, RBAC also determines the UI components and functionalities a user can access or modify. This encompasses managing dashboards, viewing notifications, using the "online mode" (which encompasses functionalities like geoip lookups, ICMP, telnet, SSH, and more), executing searches, creating or viewing triggers, running reports, and tasks. • Multiple Filters: Navigate the depth and breadth of your data. Implement filters to spotlight specific metrics, detect emerging patterns, or filter out extraneous data. • Time-Based Settings Per Widget: Data relevance can be fleeting. With unique time-based settings available for every widget, you can decide to observe data from the last hour, day, month, or any other custom duration, all encapsulated within a singular dashboard. • And Much More: While the mentioned attributes are indeed noteworthy, they merely scratch the surface of what LogZilla's dashboards have in store for any data-centric entity. In the following sections, you'll find detailed explanations of each feature, along with guidelines on how to effectively utilize them to enhance your dashboards.
__label__pos
0.602969
MPLAB Debug Express Lesson 5: Using Timer0 Discussion in 'Embedded Systems and Microcontrollers' started by NGinuity, Jun 23, 2012. 1. NGinuity Thread Starter New Member Jun 23, 2012 9 0 Hey everybody. I am going through the lessons for Pickit 3's Debug Express and I am a little stuck on Lesson 5, which introduces the use of Timer0. I have Pickit3 connected to the Development Board, and I am using USB to power the target. I took the lesson code directly from the install, built it, no errors, program the chip, no errors. The problem is that the output does not work as expected. It's supposed to shift through the LED's, incrementing or decrementing when Timer0 expires and resets, and shift direction when the input button is pressed. Unfortunately, it doesn't do anything. This is the first issue I have had with it and all other lessons have worked great! Here's the Lesson 5 C code. Can anyone see a glaring error that's causing it to hiccup? I'm a decent C coder but admittedly, I don't know the hardware that well yet. Thanks in advance for any help provided. -Eric Code ( (Unknown Language)): 1.   2. /** C O N F I G U R A T I O N   B I T S ******************************/ 3.   4. #pragma config FOSC = INTIO67, FCMEN = OFF, IESO = OFF                      // CONFIG1H 5. #pragma config PWRT = OFF, BOREN = OFF, BORV = 30                           // CONFIG2L 6. #pragma config WDTEN = OFF, WDTPS = 32768                                   // CONFIG2H 7. #pragma config MCLRE = ON, LPT1OSC = OFF, PBADEN = ON, CCP2MX = PORTC       // CONFIG3H 8. #pragma config STVREN = ON, LVP = OFF, XINST = OFF                          // CONFIG4L 9. #pragma config CP0 = OFF, CP1 = OFF, CP2 = OFF, CP3 = OFF                   // CONFIG5L 10. #pragma config CPB = OFF, CPD = OFF                                         // CONFIG5H 11. #pragma config WRT0 = OFF, WRT1 = OFF, WRT2 = OFF, WRT3 = OFF               // CONFIG6L 12. #pragma config WRTB = OFF, WRTC = OFF, WRTD = OFF                           // CONFIG6H 13. #pragma config EBTR0 = OFF, EBTR1 = OFF, EBTR2 = OFF, EBTR3 = OFF           // CONFIG7L 14. #pragma config EBTRB = OFF                                                  // CONFIG7H 15.   16.   17. /** I N C L U D E S **************************************************/ 18. #include "p18f45k20.h" 19. //#include "delays.h"  // no longer being used. 20. #include "05 Timer.h"  // header file 21.   22. /** V A R I A B L E S *************************************************/ 23. #pragma udata   // declare statically allocated uinitialized variables 24. unsigned char LED_Display;  // 8-bit variable 25.   26. /** D E C L A R A T I O N S *******************************************/ 27. #pragma code    // declare executable instructions 28.   29. void main (void) 30. { 31.     LEDDirections Direction = LEFT2RIGHT; 32.     BOOL SwitchPressed = FALSE; 33.   34.     LED_Display = 1;            // initialize 35.   36.     // Init I/O 37.     TRISD = 0b00000000;         // PORTD bits 7:0 are all outputs (0) 38.   39.     INTCON2bits.RBPU = 0;        // enable PORTB internal pullups 40.     WPUBbits.WPUB0 = 1;            // enable pull up on RB0 41.     ANSELH = 0x00;              // AN8-12 are digital inputs (AN12 on RB0) 42.   43.     TRISBbits.TRISB0 = 1;       // PORTB bit 0 (connected to switch) is input (1) 44.   45.     // Init Timer 46.     INTCONbits.TMR0IF = 0;          // clear roll-over interrupt flag 47.     T0CON = 0b00001000;             // no prescale - increments every instruction clock 48.     //T0CON = 0b00000001;             // prescale 1:4 - four times the delay. 49.     TMR0H = 0;                      // clear timer - always write upper byte first 50.     TMR0L = 0; 51.     T0CONbits.TMR0ON = 1;           // start timer 52.   53.     while (1) 54.     { 55.   56.         if (Direction == LEFT2RIGHT) 57.         { 58.             LED_Display <<= 1;          // rotate display by 1 from 0 to 7 59.             if (LED_Display == 0) 60.                 LED_Display = 1;        // rotated bit out, so set bit 0 61.         } 62.         if (Direction == RIGHT2LEFT) 63.         { 64.             LED_Display >>= 1;          // rotate display by 1 from 7 to 0 65.             if (LED_Display == 0) 66.                 LED_Display = 0x80;     // rotated bit out, so set bit 7 67.        } 68.   69.         LATD = LED_Display;         // output LED_Display value to PORTD LEDs 70.   71.         do 72.         { // poll the switch while waiting for the timer to roll over. 73.             if (Switch_Pin == 1) 74.             { // look for switch released. 75.                 SwitchPressed = FALSE; 76.             } 77.             else if (SwitchPressed == FALSE) // && (Switch_Pin == 0) due to if-else 78.             { // switch was just pressed 79.                 SwitchPressed = TRUE; 80.                 // change  direction 81.                 if (Direction == LEFT2RIGHT) 82.                     Direction = RIGHT2LEFT; 83.                 else 84.                     Direction = LEFT2RIGHT; 85.             } 86.   87.         } while (INTCONbits.TMR0IF == 0); 88.   89.         // Timer expired 90.         INTCONbits.TMR0IF = 0;          // Reset Timer flag 91.   92.     } 93.     94. } 95.     2. ErnieM AAC Fanatic! Apr 24, 2011 7,519 1,649 Well you started off the right way with a set of "known good" items (board, programmer, and code) then... oops. Did it build correctly? Does the program verify? Does the last lesson you ran still work?   3. NGinuity Thread Starter New Member Jun 23, 2012 9 0 Hi Ernie, Yes, it builds and verifies correctly, and every lesson I ran still works. When this one failed, the first thing I did to rule out hardware failure was I went back and reprogrammed it with Lesson 4 (which increments the LED when an input switch is pressed). It worked just fine.   4. THE_RB AAC Fanatic! Feb 11, 2008 5,435 1,306 Don;t you have to turn TMR0 ON in the 18F45k20?? I think one bit in the T0CON register turns the timer on.   5. ErnieM AAC Fanatic! Apr 24, 2011 7,519 1,649 I don't have anything good to add. I tried building the project (I have the files not the hardware from the Debug Express) and it simulates fine for me. I went as far as to replace their code with your code and it still builds and simulates, at least I could see how the LEDs would turn on in step. Check the include path and lib paths are correct. I also deleted the linker script inside the project as the standard script applies. I included my project with has your code but the hex file may work better.   6. NGinuity Thread Starter New Member Jun 23, 2012 9 0 Hi THE_RB, I am using this code to set up the timer for the TOCON register... if there's something more to set up TMR0, I don't know about it, but as I understand it, the value I am using for TOCON sets up the timer to increment once a cycle (no prescaler) Code ( (Unknown Language)): 1.     // Init Timer 2.     INTCONbits.TMR0IF = 0;          // clear roll-over interrupt flag 3.     T0CON = 0b00001000;             // no prescale - increments every instruction clock 4.     //T0CON = 0b00000001;             // prescale 1:4 - four times the delay. 5.     TMR0H = 0;                      // clear timer - always write upper byte first 6.     TMR0L = 0; 7.     T0CONbits.TMR0ON = 1;           // start timer Ernie, I'm not totally sure what is going on, but I went on to lesson 7, which is basically the same thing as 5, except it adds the potentiometer to control the speed of the increment using ADC. It worked fine, didn't touch the code one bit. Came back to it today, reprogrammed the chip and it isn't working like 5 now.   7. takao21203 Distinguished Member Apr 28, 2012 3,578 463 what I do in cases like that is to attach a LED, then try to blink it, if this also fails, I try just simply to switch it on somewhere. If I can switch it on, I know at least the PIC is running. If there are dynamic signals emitted, I attach a piezo speaker from which I get noise, if the signal is present. I solved almost all problems with the help of LEDs and piezo speaker.   8. NGinuity Thread Starter New Member Jun 23, 2012 9 0 Hi takao, This is the Debug Express development board so I've got LED's mounted by default on all of these outputs. The program just goes screwy for some reason. I can do anything up to introducing anything from TMR0 and it works just fine, same file locations for standard header and linker files and I don't see anything with the configuration bits either. It's really weird.   9. NGinuity Thread Starter New Member Jun 23, 2012 9 0 Ok, I managed to get it to work, but I am still a little baffled as to why I am incurring some behavior. Whenever I invoke anything from TMR0, and program the target board (or have it interact with MPLAB at all, including verify or read), for some reason it doesn't work properly until I do a hard reset on the development board. I suspect it has something to do with the timer being interacted on strangely by the programmer, but can anyone tell me why this is the case?   10. takao21203 Distinguished Member Apr 28, 2012 3,578 463 what's the setting of the /DEBUG configuration bit? Is this off?   11. NGinuity Thread Starter New Member Jun 23, 2012 9 0 I don't even think it's set. Here's what my configuration block looks like: Code ( (Unknown Language)): 1. #pragma config FOSC = INTIO67, FCMEN = OFF, IESO = OFF                      // CONFIG1H 2. #pragma config PWRT = OFF, BOREN = OFF, BORV = 30                           // CONFIG2L 3. #pragma config WDTEN = OFF, WDTPS = 32768                                   // CONFIG2H 4. #pragma config MCLRE = ON, LPT1OSC = OFF, PBADEN = ON, CCP2MX = PORTC       // CONFIG3H 5. #pragma config STVREN = ON, LVP = OFF, XINST = OFF                          // CONFIG4L 6. #pragma config CP0 = OFF, CP1 = OFF, CP2 = OFF, CP3 = OFF                   // CONFIG5L 7. #pragma config CPB = OFF, CPD = OFF                                         // CONFIG5H 8. #pragma config WRT0 = OFF, WRT1 = OFF, WRT2 = OFF, WRT3 = OFF               // CONFIG6L 9. #pragma config WRTB = OFF, WRTC = OFF, WRTD = OFF                           // CONFIG6H 10. #pragma config EBTR0 = OFF, EBTR1 = OFF, EBTR2 = OFF, EBTR3 = OFF           // CONFIG7L 11. #pragma config EBTRB = OFF                                                  // CONFIG7H Is there somewhere else I should look for it? (Sorry, I'm neeeeew :D)   12. takao21203 Distinguished Member Apr 28, 2012 3,578 463 yes there is a menu topic to see the actual configuration bits. Sorry I can't look for legacy MPLAB, have MPLAB X installed here. It's ON by default for some PICs I think.   13. NGinuity Thread Starter New Member Jun 23, 2012 9 0 I found it. The menu option for configuration bits has "Configuration Bits set in code" checked, it's not doing any overrides from the looks of it. I looked at the datasheet for the PIC18F4520 and Debug falls under CONFIG4L in the 7th bit. It looks like it is set to 1 by default and the datasheet (http://ww1.microchip.com/downloads/en/DeviceDoc/39631E.pdf Page 255) says:   14. lampi New Member Jul 29, 2012 1 0 The source code for lesson 05 is wrong. It has: #pragma config MCLRE = ON It should be: #pragma config MCLRE = OFF In order to make the program work as originally written, you have to disconnect the Pickit 3 from the eval board after programming and apply a different power supply to the PIC. That is because, with the MCLRE = ON, the Master Clear input is enabled and the Pickit 3 keeps the PIC in reset. So turn it off, MCLRE = OFF, to run lesson 05. For lesson 06 you'll need to turn it back on, MCLRE = ON, to enable debugging.   Loading...
__label__pos
0.902884
Tile Collision Ph33rles • Posts: 3 Hey all, I was exploring around through the editors and what not so I tried creating a "new game" by opening the default space shooter game that came with it. I decided to try and modify it to see if things would change as I expected. I tried to turn change the collisions so the bullets and the players would collide with the tiles so the obstacles would actually obstruct the player and bullets, however after turning on these collisions nothing had changed even after a save and reload of the test scene. Outside of turning on the collision groups is there something else I'm missing? Blob • * • Posts: 722 Make sure the tiles actually have collision boxes themselves by opening them up in the tileset menu. Also make sure all of the actor's collision boxes aren't marked as sensors. ~ Blob Ph33rles • Posts: 3 Hey Blob thanks. I actually went through and explored more and discovered that as well, and I've gotten both my player ship and the enemy bullets to interact with the tiles, however the player shots still are not stopped by the shots. After trying your advice on turning off the sensor option, the player shots still aren't interacting with the tiles, and the enemies requiring multiple shots are now bouncing backwards across the screen after being hit. This still leaves me with my original issue and I don't see the differences between the two actors of the enemies bullets and the player's bullets that would keep one colliding with the tiles and one not. Ph33rles • Posts: 3 I just figured it out, the bullets were set to cannot be pushed in the physics which was preventing it from colliding and turning it back to normal allows it to collide with the environment, but I have to admit I'm slightly confused about why it was able to collide with enemies when set like that but not with tiles. Blob • * • Posts: 722 I think the reason is it has a behavior that specifically tells it to die when it hits an actor, but not a tile. If you want the same effect for tiles, you can add it into the behavior alongside hitting an actor. ~ Blob
__label__pos
0.65995
Different type of Collections in JavaScript 1629 days ago, 0 views. When you are using a programming language, you need use something for keep your data information. Someting as a container. For do it you need to use data structure, that defines a particular way to organizing the data. Collection is a type of data structure that implement some kind of iterable interface and they internally use the same iteration method. This is easy to view in language like Java when exist a inheritance hierarchy defined by an interface. In JavaScript is similar, but is less complete and, because is not possible define interfaces, we use the inheritance based in Object . Object, Array and Functions The first thing that you need to understand is that everything is a object in JavaScript unless primitives types, that are: boolean, number, string, null, undefined About the collections, basically an object, array and function are instance of object, so you can use as data structures. The difference how to internally the iteration is defined. If you check functional libraries as lodash you can see that exist method for collection and methods specific for arrays and objects. Exists little differences between them that determine how they should be iterated: For example, an array is a collection of element in order, while object is a collection of keys, and is not important the order. But consider an Object (and Functions) as data structure at this moment with a ECMAScript6 is an error: Now we have a explicit class for do it. Map A Map is the new ECMAScript6 data structure. You can use a Object as a Map, but this have some problems: Set This is another new ECMAScript6 data structure. Is the same that Map, but only can store for unique values. WeakMap & WeakSet First we need to understand what is a Weak Reference and how works the reference in JavaScript. All things in JavaScript unless primitives types (remember the first lines of this posts) works with references. If you create a new object that reference another object, basically you are linking the reference, not copy the object into another new: var var1 = {} var var2 = var1 var1.foo = 123 // => 123 var2.foo // => 123 Basically a clone method that is very typical in other language doesn’t exist natively. When you use a Map or Set, internally the data structure is created using two arrays: One for store the key and one for store the value that is saved clone the value, not with linking method. With WeakMap and WeakSet we use collections that store the key based in how works object natively: we are telling the garbage collector can remove the value if there is no reference. Because of references being weak, WeakMap keys are not enumerable (i.e. there is no method giving you a list of the keys). If they were, the list would depend on the state of garbage collection, introducing non-determinism. If you want to have a list of keys, you should maintain it yourself. A little example about the difference of behaivor between Map and WeakMap: var map = new Map() // => {} var foo = 'bar' // => undefined map.set('foo', foo) // => {} var wmap = new WeakMap() // => {} var obj = { foo: 'bar' } // => undefined map.get('foo') // => 'bar' foo = 'it was changed' // => 'it was changed' map.get('foo') // => 'bar' wmap.set(obj, 'bar') // => {} map.get('foo') // => 'bar' wmap.get(objt) // => 'bar' obj = { foo: 'test' } // => { foo: 'test' } wmap.get(obj) // => undefined You need more? Maybe you throw at fault other data structures. What’s happens with Heap, List, MultiMap? Of course you can create this data structures based in others, but are not available nativelly. I recommend use the library collections that provide you more data structures and the native . But I miss more interesting structures such as Tree, B-Tree. References Kiko Beats Kiko Beats
__label__pos
0.941974
MikroTik RouterOS < 6.38.4 (MIPSBE) - 'Chimay Red' Stack Clash Remote Code Execution EDB-ID: 44283 CVE: N/A Platform: Hardware Date: 2018-03-12 Become a Certified Penetration Tester Enroll in Penetration Testing with Kali Linux and pass the exam to become an Offensive Security Certified Professional (OSCP). All new content for 2020. GET CERTIFIED #!/usr/bin/env python3 # Mikrotik Chimay Red Stack Clash Exploit by BigNerd95 # Tested on RouterOS 6.38.4 (mipsbe) [using a CRS109] # Used tools: pwndbg, rasm2, mipsrop for IDA # I used ropper only to automatically find gadgets # ASLR enabled on libs only # DEP NOT enabled import socket, time, sys, struct, re from ropper import RopperService AST_STACKSIZE = 0x800000 # default stack size per thread (8 MB) ROS_STACKSIZE = 0x20000 # newer version of ROS have a different stack size per thread (128 KB) SKIP_SPACE = 0x1000 # 4 KB of "safe" space for the stack of thread 2 ROP_SPACE = 0x8000 # we can send 32 KB of ROP chain! ALIGN_SIZE = 0x10 # alloca align memory with "content-length + 0x10 & 0xF" so we need to take it into account ADDRESS_SIZE = 0x4 # we need to overwrite a return address to start the ROP chain class MyRopper(): def __init__(self, filename): self.rs = RopperService() self.rs.clearCache() self.rs.addFile(filename) self.rs.loadGadgetsFor() self.rs.options.inst_count = 10 self.rs.loadGadgetsFor() self.rs.loadGadgetsFor() # sometimes Ropper doesn't update new gadgets def get_gadgets(self, regex): gadgets = [] for _, g in self.rs.search(search=regex): gadgets.append(g) if len(gadgets) > 0: return gadgets else: raise Exception("Cannot find gadgets!") def contains_string(self, string): s = self.rs.searchString(string) t = [a for a in s.values()][0] return len(t) > 0 def get_arch(self): return self.rs.files[0].arch._name @staticmethod def get_ra_offset(gadget): """ Return the offset of next Retun Address on the stack So you know how many bytes to put before next gadget address Eg: lw $ra, 0xAB ($sp) --> return: 0xAB """ for line in gadget.lines: offset_len = re.findall("lw \$ra, (0x[0-9a-f]+)\(\$sp\)", line[1]) if offset_len: return int(offset_len[0], 16) raise Exception("Cannot find $ra offset in this gadget!") def makeHeader(num): return b"POST /jsproxy HTTP/1.1\r\nContent-Length: " + bytes(str(num), 'ascii') + b"\r\n\r\n" def makeSocket(ip, port): s = socket.socket() try: s.connect((ip, port)) except: print("Error connecting to socket") sys.exit(-1) print("Connected") time.sleep(0.5) return s def socketSend(s, data): try: s.send(data) except: print("Error sending data") sys.exit(-1) print("Sent") time.sleep(0.5) def build_shellcode(shellCmd): shell_code = b'' shellCmd = bytes(shellCmd, "ascii") # Here the shellcode will write the arguments for execve: ["/bin/bash", "-c", "shellCmd", NULL] and [NULL] # XX XX XX XX <-- here the shell code will write the address of string "/bin/bash" [shellcode_start_address -16] <--- argv_array # XX XX XX XX <-- here the shell code will write the address of string "-c" [shellcode_start_address -12] # XX XX XX XX <-- here the shell code will write the address of string "shellCmd" [shellcode_start_address -8] # XX XX XX XX <-- here the shell code will write 0x00000000 (used as end of argv_array and as envp_array) [shellcode_start_address -4] <--- envp_array # The shell code execution starts here! shell_code += struct.pack('>L', 0x24500000) # addiu s0, v0, 0 # s0 = v0 Save the shellcode_start_address in s0 (in v0 we have the address of the stack where the shellcode starts [<-- pointing to this location exactly]) shell_code += struct.pack('>L', 0x24020fa2) # addiu v0, zero, 0xfa2 # v0 = 4002 (fork) Put the syscall number of fork (4002) in v0 shell_code += struct.pack('>L', 0x0000000c) # syscall # launch syscall Start fork() shell_code += struct.pack('>L', 0x10400003) # beqz v0, 0x10 # jump 12 byte forward if v0 == 0 Jump to execve part of the shellcode if PID is 0 # if v0 != 0 [res of fork()] shell_code += struct.pack('>L', 0x24020001) # addiu v0, zero, 1 # a0 = 1 Put exit parameter in a0 shell_code += struct.pack('>L', 0x24020fa1) # addiu v0, zero, 0xfa1 # v0 = 4001 (exit) Put the syscall number of exit (4002) in v0 shell_code += struct.pack('>L', 0x0000000c) # syscall # launch syscall Start exit(1) # if v0 == 0 [res of fork()] shell_code += struct.pack('>L', 0x26040050) # addiu a0, s0, 0x50 # a0 = shellcode_start_address + 0x50 Calculate the address of string "/bin/bash" and put it in a0 (the first parameter of execve) shell_code += struct.pack('>L', 0xae04fff0) # sw a0, -16(s0) # shellcode_start_address[-16] = bin_bash_address Write in the first entry of the "argv" array the address of the string "/bin/bash" shell_code += struct.pack('>L', 0x26110060) # addiu s1, s0, 0x60 # s1 = shellcode_start_address + 0x60 Calculate the address of string "-c" and put it in s1 shell_code += struct.pack('>L', 0xae11fff4) # sw s1, -12(s0) # shellcode_start_address[-12] = c_address Write in the second entry of the "argv" array the address of the string "-c" shell_code += struct.pack('>L', 0x26110070) # addiu s1, s0, 0x70 # s1 = shellcode_start_address + 0x70 Calculate the address of string "shellCmd" and put it in s1 shell_code += struct.pack('>L', 0xae11fff8) # sw s1, -8(s0) # shellcode_start_address[-8] = shellCmd_address Write in the third entry of the "argv" array the address of the string "shellCmd" shell_code += struct.pack('>L', 0xae00fffc) # sw zero, -4(s0) # shellcode_start_address[-4] = 0x00 Write NULL address as end of argv_array and envp_array shell_code += struct.pack('>L', 0x2205fff0) # addi a1, s0, -16 # a1 = shellcode_start_address - 16 Put the address of argv_array in a1 (the second parameter of execve) shell_code += struct.pack('>L', 0x2206fffc) # addi a2, s0, -4 # a2 = shellcode_start_address - 4 Put the address of envp_array in a2 (the third parameter of execve) shell_code += struct.pack('>L', 0x24020fab) # addiu v0, zero, 0xfab # v0 = 4011 (execve) Put the syscall number of execve (4011) in v0 (https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/arch/mips/include/uapi/asm/unistd.h) shell_code += struct.pack('>L', 0x0000000c) # syscall # launch syscall Start execve("/bin/bash", ["/bin/bash", "-c", "shellCmd", NULL], [NULL]) shell_code += b'P' * (0x50 - len(shell_code)) # offset to simplify string address calculation shell_code += b'/bin/bash\x00' # (Warning: do not exceed 16 bytes!) [shellcode_start + 0x50] <--- bin_bash_address shell_code += b'P' * (0x60 - len(shell_code)) # offset to simplify string address calculation shell_code += b'-c\x00' # (Warning: do not exceed 16 bytes!) [shellcode_start + 0x60] <--- c_address shell_code += b'P' * (0x70 - len(shell_code)) # offset to simplify string address calculation shell_code += shellCmd + b'\x00' # [shellcode_start + 0x70] <--- shellCmd_address return shell_code def build_payload(binRop, shellCmd): print("Building shellcode + ROP chain...") ropChain = b'' shell_code = build_shellcode(shellCmd) # 1) Stack finder gadget (to make stack pivot) stack_finder = binRop.get_gadgets("addiu ?a0, ?sp, 0x18; lw ?ra, 0x???(?sp% jr ?ra;")[0] """ 0x0040ae04: (ROS 6.38.4) addiu $a0, $sp, 0x18 <--- needed action lw $ra, 0x5fc($sp) <--- jump control [0x5fc, a lot of space for the shellcode!] lw $s3, 0x5f8($sp) lw $s2, 0x5f4($sp) lw $s1, 0x5f0($sp) lw $s0, 0x5ec($sp) move $v0, $zero jr $ra """ ropChain += struct.pack('>L', stack_finder.address) # Action: addiu $a0, $sp, 0x600 + var_5E8 # a0 = stackpointer + 0x18 # Control Jump: jr 0x600 + var_4($sp) # This gadget (moreover) allows us to reserve 1512 bytes inside the rop chain # to store the shellcode (beacuse of: jr 0x600 + var_4($sp)) ropChain += b'B' * 0x18 # 0x600 - 0x5E8 = 0x18 (in the last 16 bytes of this offset the shell code will write the arguments for execve) ropChain += shell_code # write the shell code in this "big" offset next_gadget_offset = MyRopper.get_ra_offset(stack_finder) - 0x18 - len(shell_code) if next_gadget_offset < 0: # check if shell command fits inside this big offset raise Exception("Shell command too long! Max len: " + str(next_gadget_offset + len(shellCmd)) + " bytes") ropChain += b'C' * next_gadget_offset # offset because of this: 0x600 + var_4($sp) # 2) Copy a0 in v0 because of next gadget mov_v0_a0 = binRop.get_gadgets("lw ?ra, %move ?v0, ?a0;% jr ?ra;")[0] """ 0x00414E58: (ROS 6.38.4) lw $ra, 0x24($sp); <--- jump control lw $s2, 0x20($sp); lw $s1, 0x1c($sp); lw $s0, 0x18($sp); move $v0, $a0; <--- needed action jr $ra; """ ropChain += struct.pack('>L', mov_v0_a0.address) # Gadget Action: move $v0, $a0 # v0 = a0 # Gadget Control: jr 0x28 + var_4($sp) ropChain += b'D' * MyRopper.get_ra_offset(mov_v0_a0) # offset because of this: 0x28 + var_4($sp) # 3) Jump to the stack (start shell code) jump_v0 = binRop.get_gadgets("move ?t9, ?v0; jalr ?t9;")[0] """ 0x00412540: (ROS 6.38.4) move $t9, $v0; <--- jump control jalr $t9; <--- needed action """ ropChain += struct.pack('>L', jump_v0.address) # Gadget Action: jalr $t9 # jump v0 # Gadget Control: jalr $v0 return ropChain def stackClash(ip, port, payload): print("Opening 2 sockets") # 1) Start 2 threads # open 2 socket so 2 threads are created s1 = makeSocket(ip, port) # socket 1, thread A s2 = makeSocket(ip, port) # socket 2, thread B print("Stack clash...") # 2) Stack Clash # 2.1) send post header with Content-Length bigger than AST_STACKSIZE to socket 1 (thread A) socketSend(s1, makeHeader(AST_STACKSIZE + SKIP_SPACE + ROP_SPACE)) # thanks to alloca, the Stack Pointer of thread A will point inside the stack frame of thread B (the post_data buffer will start from here) # 2.2) send some bytes as post data to socket 1 (thread A) socketSend(s1, b'A'*(SKIP_SPACE - ALIGN_SIZE - ADDRESS_SIZE)) # increase the post_data buffer pointer of thread A to a position where a return address of thread B will be saved # 2.3) send post header with Content-Length to reserve ROP space to socket 2 (thread B) socketSend(s2, makeHeader(ROP_SPACE)) # thanks to alloca, the Stack Pointer of thread B will point where post_data buffer pointer of thread A is positioned print("Sending payload") # 3) Send ROP chain and shell code socketSend(s1, payload) print("Starting exploit") # 4) Start ROP chain s2.close() # close socket 2 to return from the function of thread B and start ROP chain print("Done!") def crash(ip, port): print("Crash...") s = makeSocket(ip, port) socketSend(s, makeHeader(-1)) socketSend(s, b'A' * 0x1000) s.close() time.sleep(2.5) # www takes up to 3 seconds to restart if __name__ == "__main__": if len(sys.argv) == 5: ip = sys.argv[1] port = int(sys.argv[2]) binary = sys.argv[3] shellCmd = sys.argv[4] binRop = MyRopper(binary) if binRop.get_arch() != 'MIPSBE': raise Exception("Wrong architecture! You have to pass a mipsbe executable") if binRop.contains_string("pthread_attr_setstacksize"): AST_STACKSIZE = ROS_STACKSIZE payload = build_payload(binRop, shellCmd) crash(ip, port) # should make stack clash more reliable stackClash(ip, port, payload) else: print("Usage: " + sys.argv[0] + " IP PORT binary shellcommand")
__label__pos
0.55775
How do you simplify #(-6c^3)/(2c^4 8c^2)#? 1 Answer Dec 22, 2015 # =color(blue)( (-3)/(8c^3)# Explanation: #(-6c^3)/(2c^(4)8c^2)# # =color(blue)(( (-6)/(2xx8)) )xx (c^3)/(c^(4)c^2)# # =color(blue)(( (-6)/(16)) )xx (c^3)/(c^(4)c^2)# As per property of exponents #color(blue)(a^m * a^n=a^(m+n)# #color(blue)(a^m / a^n=a^(m-n)# Applying the above to the exponents of #c#: # =color(blue)(( (-6)/(16)) )xx (c^3)/(c^color(blue)((4+2))# # =( (-6)/(16) )xx (c^3)/(c^color(blue)(6)# # =( cancel(-6)/(cancel16) )xx (c^(3-6))# # =( (-3)/(8)) xx (c^(-3))# As per property #color(blue)(a^-1=1/a# # =color(blue)( (-3)/(8c^3)#
__label__pos
0.999952
Computer Software How does bit rate affect the sound quality of your MP3 file? Answered by HowStuffWorks • HowStuffWorks HowStuffWorks 1. A music file's bit rate refers to the number of bits each second-long music sample contains. A music file on a CD contains 16 bits of data for each of its 44,100 samples, but an MP3 file discards some of those bits, using compression to create a smaller file size. You can create different MP3 files with different sound quality for the same song, because most compression and encoding software lets you choose the bit rate you want. The lower the bit rate, the more data that is lost compared with the original file, and bit rates typically range from 96 to 320 kilobytes per second (Kbps). It generally takes a bit rate of 160 Kbps or above to produce sound quality comparable to a CD. Though the MP3 music file format revolutionized the distribution of music, some people who value the best possible music experience look down on MP3s. These audiophiles believe that MP3s, no matter how high their bit rates, are inferior to vinyl records and CDs. Others argue that the human ear could never hear the data that's lost to create a 320-Kbps bit rate song in the first place, so they say there is effectively no difference. Many musicians also believe that songs are increasingly being recorded with fewer variations in volume and pitch, to accommodate the MP3 format, which results in inferior recordings and music with a generic sound. It's useful to note that MP3 wasn't the end of the line for media compression that could help consumers and producers alike. There is also the MP4 compression format, which is typically used for video, audio and multimedia content. (The MP3 format, by contrast, is for audio only.) Content that can be streamed -- for example, an Internet podcast -- is often created and distributed in the MP4 format. A multitude of media players will play files in the format, including the iPod. More answers from HowStuffWorks » Still Curious? • Does the government need a warrant to search my computer? Answered by Animal Planet • What is Adobe Systems? Answered by Discovery Channel • Will augmented reality technology be 3D compatible? Answered by Yi Wu
__label__pos
0.990228
Authors Top If you have a few years of experience in Computer Science or research, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines. 1. Introduction Variables play an important role in computer programming because they enable programmers to write flexible programs. A very important aspect that we need to keep in mind with variables is when we pass variables them as arguments to a function. This tutorial explores what happens under the hood when the caller of a function passes arguments to the callee by value and by reference. 2. Call by Value Call by value, also known as pass by value, is the most common way of passing arguments. When we pass a parameter by value, the caller and callee have two independent variables with the same value. Therefore, if the callee modifies its variable, the effect is not visible to the caller. Indeed, it has its own copy of the variable: Rendered by QuickLaTeX.com Rendered by QuickLaTeX.com In the example above, the caller creates a variable a and assigns the value 5 to it. At this point, when we print the value of a we clearly get 5 as a result. The crucial step is when the caller calls the callee, passing the variable a by value. The operating system creates a new independent variable x with the same value as a. When the callee modifies the variable x by simply adding 1 to it, the effects cannot be seen by the caller. Indeed, when the caller prints the a variable for the second time, we still get 5 as a result. 3. Call by Reference When we pass a variable by reference, the parameter inside the callee refers to the same object that the caller passed. As a consequence, any change operated by the callee on the object will be seen by the caller as well. In other words, when a parameter is passed by reference, the caller and the callee use the same variable. If the function being called modifies this variable, the effect is visible to the caller’s variable: Rendered by QuickLaTeX.com Rendered by QuickLaTeX.com As in the previous example, the caller creates a variable a and assigns the value 5 to it. When we print it, we get 5 as a result. Then, the caller calls the callee, passing the variable a by reference. The operating system creates an implicit reference x to variable a, rather than a brand new variable containing a copy of a‘s value. When the callee adds 1 to x, the effects can be seen by the caller. Indeed, the subsequent print statement returns 6 as a result. 4. Call by Value and Call by Reference in Modern Languages Modern programming languages usually store data on the heap. Only “pointers” to it are ever held in variables and passed as parameters. Passing such a pointer is still pass by value because a variable’s value is technically the pointer itself, not the pointed object. However, the final effect on the program can be the same as either pass by value or pass by reference: • If the caller passes a pointer to the callee, this has the same effect as pass by reference. Indeed, the caller will see the changes to the referred object. However, if the callee reassigns the variable holding this pointer then the variable will stop pointing to that object. Any further operations on this variable will instead affect whatever it is pointing to now. • If the caller passes a deep copy of an object to the callee then we can have the same effect as pass by value. Moreover, some programming languages have “immutable” types which always have the effect of the call by value when we pass them as arguments. By using call by reference, we have access to an additional channel of communication between the called function and the calling function. However, passing a variable by reference makes it more difficult to track the effects of a function call, and may introduce subtle bugs. 5. Conclusion In this article, we’ve introduced the concepts of pass by value and pass by reference. Authors Bottom If you have a few years of experience in Computer Science or research, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines. Comments are closed on this article!
__label__pos
0.649152
HTML Forms API Forms in HTML documents are represented by mechanize.HTMLForm. Every form is a collection of controls. The different types of controls are represented by the various classes documented below. class mechanize.HTMLForm(action, method='GET', enctype='application/x-www-form-urlencoded', name=None, attrs=None, request_class=<class mechanize._request.Request>, forms=None, labels=None, id_to_labels=None)[source] Represents a single HTML <form> … </form> element. A form consists of a sequence of controls that usually have names, and which can take on various values. The values of the various types of controls represent variously: text, zero-or-one-of-many or many-of-many choices, and files to be uploaded. Some controls can be clicked on to submit the form, and clickable controls’ values sometimes include the coordinates of the click. Forms can be filled in with data to be returned to the server, and then submitted, using the click method to generate a request object suitable for passing to mechanize.urlopen() (or the click_request_data or click_pairs methods for integration with third-party code). Usually, HTMLForm instances are not created directly. Instead, they are automatically created when visting a page with a mechanize Browser. If you do construct HTMLForm objects yourself, however, note that an HTMLForm instance is only properly initialised after the fixup method has been called. See mechanize.ListControl for the reason this is required. Indexing a form (form[“control_name”]) returns the named Control’s value attribute. Assignment to a form index (form[“control_name”] = something) is equivalent to assignment to the named Control’s value attribute. If you need to be more specific than just supplying the control’s name, use the set_value and get_value methods. ListControl values are lists of item names (specifically, the names of the items that are selected and not disabled, and hence are “successful” – ie. cause data to be returned to the server). The list item’s name is the value of the corresponding HTML element’s”value” attribute. Example: <INPUT type="CHECKBOX" name="cheeses" value="leicester"></INPUT> <INPUT type="CHECKBOX" name="cheeses" value="cheddar"></INPUT> defines a CHECKBOX control with name “cheeses” which has two items, named “leicester” and “cheddar”. Another example: <SELECT name="more_cheeses"> <OPTION>1</OPTION> <OPTION value="2" label="CHEDDAR">cheddar</OPTION> </SELECT> defines a SELECT control with name “more_cheeses” which has two items, named “1” and “2” (because the OPTION element’s value HTML attribute defaults to the element contents – see mechanize.SelectControl for more on these defaulting rules). To select, deselect or otherwise manipulate individual list items, use the mechanize.HTMLForm.find_control() and mechanize.ListControl.get() methods. To set the whole value, do as for any other control: use indexing or the set_value/get_value methods. Example: # select *only* the item named "cheddar" form["cheeses"] = ["cheddar"] # select "cheddar", leave other items unaffected form.find_control("cheeses").get("cheddar").selected = True Some controls (RADIO and SELECT without the multiple attribute) can only have zero or one items selected at a time. Some controls (CHECKBOX and SELECT with the multiple attribute) can have multiple items selected at a time. To set the whole value of a ListControl, assign a sequence to a form index: form["cheeses"] = ["cheddar", "leicester"] If the ListControl is not multiple-selection, the assigned list must be of length one. To check if a control has an item, if an item is selected, or if an item is successful (selected and not disabled), respectively: "cheddar" in [item.name for item in form.find_control("cheeses").items] "cheddar" in [item.name for item in form.find_control("cheeses").items and item.selected] "cheddar" in form["cheeses"] # or "cheddar" in form.get_value("cheeses") Note that some list items may be disabled (see below). Note the following mistake: form[control_name] = control_value assert form[control_name] == control_value # not necessarily true The reason for this is that form[control_name] always gives the list items in the order they were listed in the HTML. List items (hence list values, too) can be referred to in terms of list item labels rather than list item names using the appropriate label arguments. Note that each item may have several labels. The question of default values of OPTION contents, labels and values is somewhat complicated: see mechanize.SelectControl and mechanize.ListControl.get_item_attrs() if you think you need to know. Controls can be disabled or readonly. In either case, the control’s value cannot be changed until you clear those flags (see example below). Disabled is the state typically represented by browsers by ‘greying out’ a control. Disabled controls are not ‘successful’ – they don’t cause data to get returned to the server. Readonly controls usually appear in browsers as read-only text boxes. Readonly controls are successful. List items can also be disabled. Attempts to select or deselect disabled items fail with AttributeError. If a lot of controls are readonly, it can be useful to do this: form.set_all_readonly(False) To clear a control’s value attribute, so that it is not successful (until a value is subsequently set): form.clear("cheeses") More examples: control = form.find_control("cheeses") control.disabled = False control.readonly = False control.get("gruyere").disabled = True control.items[0].selected = True See the various Control classes for further documentation. Many methods take name, type, kind, id, label and nr arguments to specify the control to be operated on: see mechanize.HTMLForm.find_control(). ControlNotFoundError (subclass of ValueError) is raised if the specified control can’t be found. This includes occasions where a non-ListControl is found, but the method (set, for example) requires a ListControl. ItemNotFoundError (subclass of ValueError) is raised if a list item can’t be found. ItemCountError (subclass of ValueError) is raised if an attempt is made to select more than one item and the control doesn’t allow that, or set/get_single are called and the control contains more than one item. AttributeError is raised if a control or item is readonly or disabled and an attempt is made to alter its value. Security note: Remember that any passwords you store in HTMLForm instances will be saved to disk in the clear if you pickle them (directly or indirectly). The simplest solution to this is to avoid pickling HTMLForm objects. You could also pickle before filling in any password, or just set the password to “” before pickling. Public attributes: Variables: • action – full (absolute URI) form action • method – “GET” or “POST” • enctype – form transfer encoding MIME type • name – name of form (None if no name was specified) • attrs – dictionary mapping original HTML form attributes to their values • controls – list of Control instances; do not alter this list (instead, call form.new_control to make a Control and add it to the form, or control.add_to_form if you already have a Control instance) Methods for form filling: Most of the these methods have very similar arguments. See mechanize.HTMLForm.find_control() for details of the name, type, kind, label and nr arguments. def find_control(self, name=None, type=None, kind=None, id=None, predicate=None, nr=None, label=None) get_value(name=None, type=None, kind=None, id=None, nr=None, by_label=False, # by_label is deprecated label=None) set_value(value, name=None, type=None, kind=None, id=None, nr=None, by_label=False, # by_label is deprecated label=None) clear_all() clear(name=None, type=None, kind=None, id=None, nr=None, label=None) set_all_readonly(readonly) Method applying only to FileControls: add_file(file_object, content_type="application/octet-stream", filename=None, name=None, id=None, nr=None, label=None) Methods applying only to clickable controls: click(name=None, type=None, id=None, nr=0, coord=(1,1), label=None) click_request_data(name=None, type=None, id=None, nr=0, coord=(1,1), label=None) click_pairs(name=None, type=None, id=None, nr=0, coord=(1,1), label=None) add_file(file_object, content_type=None, filename=None, name=None, id=None, nr=None, label=None)[source] Add a file to be uploaded. Parameters: • file_object – file-like object (with read method) from which to read data to upload • content_type – MIME content type of data to upload • filename – filename to pass to server If filename is None, no filename is sent to the server. If content_type is None, the content type is guessed based on the filename and the data from read from the file object. At the moment, guessed content type is always application/octet-stream. Note the following useful HTML attributes of file upload controls (see HTML 4.01 spec, section 17): • accept: comma-separated list of content types that the server will handle correctly; you can use this to filter out non-conforming files • size: XXX IIRC, this is indicative of whether form wants multiple or single files • maxlength: XXX hint of max content length in bytes? clear(name=None, type=None, kind=None, id=None, nr=None, label=None)[source] Clear the value attribute of a control. As a result, the affected control will not be successful until a value is subsequently set. AttributeError is raised on readonly controls. clear_all()[source] Clear the value attributes of all controls in the form. See mechanize.HTMLForm.clear() click(name=None, type=None, id=None, nr=0, coord=(1, 1), request_class=<class mechanize._request.Request>, label=None)[source] Return request that would result from clicking on a control. The request object is a mechanize.Request instance, which you can pass to mechanize.urlopen. Only some control types (INPUT/SUBMIT & BUTTON/SUBMIT buttons and IMAGEs) can be clicked. Will click on the first clickable control, subject to the name, type and nr arguments (as for find_control). If no name, type, id or number is specified and there are no clickable controls, a request will be returned for the form in its current, un-clicked, state. IndexError is raised if any of name, type, id or nr is specified but no matching control is found. ValueError is raised if the HTMLForm has an enctype attribute that is not recognised. You can optionally specify a coordinate to click at, which only makes a difference if you clicked on an image. click_pairs(name=None, type=None, id=None, nr=0, coord=(1, 1), label=None)[source] As for click_request_data, but returns a list of (key, value) pairs. You can use this list as an argument to urllib.urlencode. This is usually only useful if you’re using httplib or urllib rather than mechanize. It may also be useful if you want to manually tweak the keys and/or values, but this should not be necessary. Otherwise, use the click method. Note that this method is only useful for forms of MIME type x-www-form-urlencoded. In particular, it does not return the information required for file upload. If you need file upload and are not using mechanize, use click_request_data. click_request_data(name=None, type=None, id=None, nr=0, coord=(1, 1), request_class=<class mechanize._request.Request>, label=None)[source] As for click method, but return a tuple (url, data, headers). You can use this data to send a request to the server. This is useful if you’re using httplib or urllib rather than mechanize. Otherwise, use the click method. find_control(name=None, type=None, kind=None, id=None, predicate=None, nr=None, label=None)[source] Locate and return some specific control within the form. At least one of the name, type, kind, predicate and nr arguments must be supplied. If no matching control is found, ControlNotFoundError is raised. If name is specified, then the control must have the indicated name. If type is specified then the control must have the specified type (in addition to the types possible for <input> HTML tags: “text”, “password”, “hidden”, “submit”, “image”, “button”, “radio”, “checkbox”, “file” we also have “reset”, “buttonbutton”, “submitbutton”, “resetbutton”, “textarea”, “select”). If kind is specified, then the control must fall into the specified group, each of which satisfies a particular interface. The types are “text”, “list”, “multilist”, “singlelist”, “clickable” and “file”. If id is specified, then the control must have the indicated id. If predicate is specified, then the control must match that function. The predicate function is passed the control as its single argument, and should return a boolean value indicating whether the control matched. nr, if supplied, is the sequence number of the control (where 0 is the first). Note that control 0 is the first control matching all the other arguments (if supplied); it is not necessarily the first control in the form. If no nr is supplied, AmbiguityError is raised if multiple controls match the other arguments. If label is specified, then the control must have this label. Note that radio controls and checkboxes never have labels: their items do. fixup()[source] Normalise form after all controls have been added. This is usually called by ParseFile and ParseResponse. Don’t call it youself unless you’re building your own Control instances. This method should only be called once, after all controls have been added to the form. get_value(name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None)[source] Return value of control. If only name and value arguments are supplied, equivalent to form[name] get_value_by_label(name=None, type=None, kind=None, id=None, label=None, nr=None)[source] All arguments should be passed by name. new_control(type, name, attrs, ignore_unknown=False, select_default=False, index=None)[source] Adds a new control to the form. This is usually called by mechanize. Don’t call it yourself unless you’re building your own Control instances. Note that controls representing lists of items are built up from controls holding only a single list item. See mechanize.ListControl for further information. Parameters: • type – type of control (see mechanize.Control for a list) • attrs – HTML attributes of control • ignore_unknown – if true, use a dummy Control instance for controls of unknown type; otherwise, use a TextControl • select_default – for RADIO and multiple-selection SELECT controls, pick the first item as the default if no ‘selected’ HTML attribute is present (this defaulting happens when the HTMLForm.fixup method is called) • index – index of corresponding element in HTML (see MoreFormTests.test_interspersed_controls for motivation) possible_items(name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None)[source] Return a list of all values that the specified control can take. set(selected, item_name, name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None)[source] Select / deselect named list item. Parameters:selected – boolean selected state set_single(selected, name=None, type=None, kind=None, id=None, nr=None, by_label=None, label=None)[source] Select / deselect list item in a control having only one item. If the control has multiple list items, ItemCountError is raised. This is just a convenience method, so you don’t need to know the item’s name – the item name in these single-item controls is usually something meaningless like “1” or “on”. For example, if a checkbox has a single item named “on”, the following two calls are equivalent: control.toggle("on") control.toggle_single() set_value(value, name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None)[source] Set value of control. If only name and value arguments are supplied, equivalent to form[name] = value set_value_by_label(value, name=None, type=None, kind=None, id=None, label=None, nr=None)[source] All arguments should be passed by name. toggle(item_name, name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None)[source] Toggle selected state of named list item. toggle_single(name=None, type=None, kind=None, id=None, nr=None, by_label=None, label=None)[source] Toggle selected state of list item in control having only one item. The rest is as for mechanize.HTMLForm.set_single() class mechanize.Control(type, name, attrs, index=None)[source] An HTML form control. An HTMLForm contains a sequence of Controls. The Controls in an HTMLForm are accessed using the HTMLForm.find_control method or the HTMLForm.controls attribute. Control instances are usually constructed using the ParseFile / ParseResponse functions. If you use those functions, you can ignore the rest of this paragraph. A Control is only properly initialised after the fixup method has been called. In fact, this is only strictly necessary for ListControl instances. This is necessary because ListControls are built up from ListControls each containing only a single item, and their initial value(s) can only be known after the sequence is complete. The types and values that are acceptable for assignment to the value attribute are defined by subclasses. If the disabled attribute is true, this represents the state typically represented by browsers by ‘greying out’ a control. If the disabled attribute is true, the Control will raise AttributeError if an attempt is made to change its value. In addition, the control will not be considered ‘successful’ as defined by the W3C HTML 4 standard – ie. it will contribute no data to the return value of the HTMLForm.click* methods. To enable a control, set the disabled attribute to a false value. If the readonly attribute is true, the Control will raise AttributeError if an attempt is made to change its value. To make a control writable, set the readonly attribute to a false value. All controls have the disabled and readonly attributes, not only those that may have the HTML attributes of the same names. On assignment to the value attribute, the following exceptions are raised: TypeError, AttributeError (if the value attribute should not be assigned to, because the control is disabled, for example) and ValueError. If the name or value attributes are None, or the value is an empty list, or if the control is disabled, the control is not successful. Public attributes: Variables: • type (str) – string describing type of control (see the keys of the HTMLForm.type2class dictionary for the allowable values) (readonly) • name (str) – name of control (readonly) • value – current value of control (subclasses may allow a single value, a sequence of values, or either) • disabled (bool) – disabled state • readonly (bool) – readonly state • id (str) – value of id HTML attribute get_labels()[source] Return all labels (Label instances) for this control. If the control was surrounded by a <label> tag, that will be the first label; all other labels, connected by ‘for’ and ‘id’, are in the order that appear in the HTML. pairs()[source] Return list of (key, value) pairs suitable for passing to urlencode. class mechanize.ScalarControl(type, name, attrs, index=None)[source] Bases: mechanize._form_controls.Control Control whose value is not restricted to one of a prescribed set. Some ScalarControls don’t accept any value attribute. Otherwise, takes a single value, which must be string-like. Additional read-only public attribute: Variables:attrs (dict) – dictionary mapping the names of original HTML attributes of the control to their values get_labels() Return all labels (Label instances) for this control. If the control was surrounded by a <label> tag, that will be the first label; all other labels, connected by ‘for’ and ‘id’, are in the order that appear in the HTML. pairs() Return list of (key, value) pairs suitable for passing to urlencode. class mechanize.TextControl(type, name, attrs, index=None)[source] Bases: mechanize._form_controls.ScalarControl Textual input control. Covers HTML elements: INPUT/TEXT, INPUT/PASSWORD, INPUT/HIDDEN, TEXTAREA get_labels() Return all labels (Label instances) for this control. If the control was surrounded by a <label> tag, that will be the first label; all other labels, connected by ‘for’ and ‘id’, are in the order that appear in the HTML. pairs() Return list of (key, value) pairs suitable for passing to urlencode. class mechanize.FileControl(type, name, attrs, index=None)[source] Bases: mechanize._form_controls.ScalarControl File upload with INPUT TYPE=FILE. The value attribute of a FileControl is always None. Use add_file instead. Additional public method: add_file() add_file(file_object, content_type=None, filename=None)[source] Add data from the specified file to be uploaded. content_type and filename are sent in the HTTP headers if specified. get_labels() Return all labels (Label instances) for this control. If the control was surrounded by a <label> tag, that will be the first label; all other labels, connected by ‘for’ and ‘id’, are in the order that appear in the HTML. pairs() Return list of (key, value) pairs suitable for passing to urlencode. class mechanize.IgnoreControl(type, name, attrs, index=None)[source] Bases: mechanize._form_controls.ScalarControl Control that we’re not interested in. Covers html elements: INPUT/RESET, BUTTON/RESET, INPUT/BUTTON, BUTTON/BUTTON These controls are always unsuccessful, in the terminology of HTML 4 (ie. they never require any information to be returned to the server). BUTTON/BUTTON is used to generate events for script embedded in HTML. The value attribute of IgnoreControl is always None. get_labels() Return all labels (Label instances) for this control. If the control was surrounded by a <label> tag, that will be the first label; all other labels, connected by ‘for’ and ‘id’, are in the order that appear in the HTML. pairs() Return list of (key, value) pairs suitable for passing to urlencode. class mechanize.ListControl(type, name, attrs={}, select_default=False, called_as_base_class=False, index=None)[source] Bases: mechanize._form_controls.Control Control representing a sequence of items. The value attribute of a ListControl represents the successful list items in the control. The successful list items are those that are selected and not disabled. ListControl implements both list controls that take a length-1 value (single-selection) and those that take length >1 values (multiple-selection). ListControls accept sequence values only. Some controls only accept sequences of length 0 or 1 (RADIO, and single-selection SELECT). In those cases, ItemCountError is raised if len(sequence) > 1. CHECKBOXes and multiple-selection SELECTs (those having the “multiple” HTML attribute) accept sequences of any length. Note the following mistake: control.value = some_value assert control.value == some_value # not necessarily true The reason for this is that the value attribute always gives the list items in the order they were listed in the HTML. ListControl items can also be referred to by their labels instead of names. Use the label argument to .get(), and the .set_value_by_label(), .get_value_by_label() methods. Note that, rather confusingly, though SELECT controls are represented in HTML by SELECT elements (which contain OPTION elements, representing individual list items), CHECKBOXes and RADIOs are not represented by any element. Instead, those controls are represented by a collection of INPUT elements. For example, this is a SELECT control, named “control1”: <select name="control1"> <option>foo</option> <option value="1">bar</option> </select> and this is a CHECKBOX control, named “control2”: <input type="checkbox" name="control2" value="foo" id="cbe1"> <input type="checkbox" name="control2" value="bar" id="cbe2"> The id attribute of a CHECKBOX or RADIO ListControl is always that of its first element (for example, “cbe1” above). Additional read-only public attribute: multiple. fixup()[source] ListControls are built up from component list items (which are also ListControls) during parsing. This method should be called after all items have been added. See mechanize.ListControl for the reason this is required. get(name=None, label=None, id=None, nr=None, exclude_disabled=False)[source] Return item by name or label, disambiguating if necessary with nr. All arguments must be passed by name, with the exception of ‘name’, which may be used as a positional argument. If name is specified, then the item must have the indicated name. If label is specified, then the item must have a label whose whitespace-compressed, stripped, text substring-matches the indicated label string (e.g. label=”please choose” will match ” Do please choose an item “). If id is specified, then the item must have the indicated id. nr is an optional 0-based index of the items matching the query. If nr is the default None value and more than item is found, raises AmbiguityError. If no item is found, or if items are found but nr is specified and not found, raises ItemNotFoundError. Optionally excludes disabled items. get_item_attrs(name, by_label=False, nr=None)[source] Return dictionary of HTML attributes for a single ListControl item. The HTML element types that describe list items are: OPTION for SELECT controls, INPUT for the rest. These elements have HTML attributes that you may occasionally want to know about – for example, the “alt” HTML attribute gives a text string describing the item (graphical browsers usually display this as a tooltip). The returned dictionary maps HTML attribute names to values. The names and values are taken from the original HTML. get_item_disabled(name, by_label=False, nr=None)[source] Get disabled state of named list item in a ListControl. get_items(name=None, label=None, id=None, exclude_disabled=False)[source] Return matching items by name or label. For argument docs, see the docstring for .get() get_labels() Return all labels (Label instances) for this control. If the control was surrounded by a <label> tag, that will be the first label; all other labels, connected by ‘for’ and ‘id’, are in the order that appear in the HTML. get_value_by_label()[source] Return the value of the control as given by normalized labels. pairs() Return list of (key, value) pairs suitable for passing to urlencode. possible_items(by_label=False)[source] Deprecated: return the names or labels of all possible items. Includes disabled items, which may be misleading for some use cases. set(selected, name, by_label=False, nr=None)[source] Deprecated: given a name or label and optional disambiguating index nr, set the matching item’s selection to the bool value of selected. Selecting items follows the behavior described in the docstring of the ‘get’ method. if the item is disabled, or this control is disabled or readonly, raise AttributeError. set_all_items_disabled(disabled)[source] Set disabled state of all list items in a ListControl. Parameters:disabled – boolean disabled state set_item_disabled(disabled, name, by_label=False, nr=None)[source] Set disabled state of named list item in a ListControl. Parameters:disabled – boolean disabled state set_single(selected, by_label=None)[source] Deprecated: set the selection of the single item in this control. Raises ItemCountError if the control does not contain only one item. by_label argument is ignored, and included only for backwards compatibility. set_value_by_label(value)[source] Set the value of control by item labels. value is expected to be an iterable of strings that are substrings of the item labels that should be selected. Before substring matching is performed, the original label text is whitespace-compressed (consecutive whitespace characters are converted to a single space character) and leading and trailing whitespace is stripped. Ambiguous labels: it will not complain as long as all ambiguous labels share the same item name (e.g. OPTION value). toggle(name, by_label=False, nr=None)[source] Deprecated: given a name or label and optional disambiguating index nr, toggle the matching item’s selection. Selecting items follows the behavior described in the docstring of the ‘get’ method. if the item is disabled, or this control is disabled or readonly, raise AttributeError. toggle_single(by_label=None)[source] Deprecated: toggle the selection of the single item in this control. Raises ItemCountError if the control does not contain only one item. by_label argument is ignored, and included only for backwards compatibility. class mechanize.RadioControl(type, name, attrs, select_default=False, index=None)[source] Bases: mechanize._form_controls.ListControl Covers: INPUT/RADIO get(name=None, label=None, id=None, nr=None, exclude_disabled=False) Return item by name or label, disambiguating if necessary with nr. All arguments must be passed by name, with the exception of ‘name’, which may be used as a positional argument. If name is specified, then the item must have the indicated name. If label is specified, then the item must have a label whose whitespace-compressed, stripped, text substring-matches the indicated label string (e.g. label=”please choose” will match ” Do please choose an item “). If id is specified, then the item must have the indicated id. nr is an optional 0-based index of the items matching the query. If nr is the default None value and more than item is found, raises AmbiguityError. If no item is found, or if items are found but nr is specified and not found, raises ItemNotFoundError. Optionally excludes disabled items. get_item_attrs(name, by_label=False, nr=None) Return dictionary of HTML attributes for a single ListControl item. The HTML element types that describe list items are: OPTION for SELECT controls, INPUT for the rest. These elements have HTML attributes that you may occasionally want to know about – for example, the “alt” HTML attribute gives a text string describing the item (graphical browsers usually display this as a tooltip). The returned dictionary maps HTML attribute names to values. The names and values are taken from the original HTML. get_item_disabled(name, by_label=False, nr=None) Get disabled state of named list item in a ListControl. get_items(name=None, label=None, id=None, exclude_disabled=False) Return matching items by name or label. For argument docs, see the docstring for .get() get_value_by_label() Return the value of the control as given by normalized labels. pairs() Return list of (key, value) pairs suitable for passing to urlencode. possible_items(by_label=False) Deprecated: return the names or labels of all possible items. Includes disabled items, which may be misleading for some use cases. set(selected, name, by_label=False, nr=None) Deprecated: given a name or label and optional disambiguating index nr, set the matching item’s selection to the bool value of selected. Selecting items follows the behavior described in the docstring of the ‘get’ method. if the item is disabled, or this control is disabled or readonly, raise AttributeError. set_all_items_disabled(disabled) Set disabled state of all list items in a ListControl. Parameters:disabled – boolean disabled state set_item_disabled(disabled, name, by_label=False, nr=None) Set disabled state of named list item in a ListControl. Parameters:disabled – boolean disabled state set_single(selected, by_label=None) Deprecated: set the selection of the single item in this control. Raises ItemCountError if the control does not contain only one item. by_label argument is ignored, and included only for backwards compatibility. set_value_by_label(value) Set the value of control by item labels. value is expected to be an iterable of strings that are substrings of the item labels that should be selected. Before substring matching is performed, the original label text is whitespace-compressed (consecutive whitespace characters are converted to a single space character) and leading and trailing whitespace is stripped. Ambiguous labels: it will not complain as long as all ambiguous labels share the same item name (e.g. OPTION value). toggle(name, by_label=False, nr=None) Deprecated: given a name or label and optional disambiguating index nr, toggle the matching item’s selection. Selecting items follows the behavior described in the docstring of the ‘get’ method. if the item is disabled, or this control is disabled or readonly, raise AttributeError. toggle_single(by_label=None) Deprecated: toggle the selection of the single item in this control. Raises ItemCountError if the control does not contain only one item. by_label argument is ignored, and included only for backwards compatibility. class mechanize.CheckboxControl(type, name, attrs, select_default=False, index=None)[source] Bases: mechanize._form_controls.ListControl Covers: INPUT/CHECKBOX fixup() ListControls are built up from component list items (which are also ListControls) during parsing. This method should be called after all items have been added. See mechanize.ListControl for the reason this is required. get(name=None, label=None, id=None, nr=None, exclude_disabled=False) Return item by name or label, disambiguating if necessary with nr. All arguments must be passed by name, with the exception of ‘name’, which may be used as a positional argument. If name is specified, then the item must have the indicated name. If label is specified, then the item must have a label whose whitespace-compressed, stripped, text substring-matches the indicated label string (e.g. label=”please choose” will match ” Do please choose an item “). If id is specified, then the item must have the indicated id. nr is an optional 0-based index of the items matching the query. If nr is the default None value and more than item is found, raises AmbiguityError. If no item is found, or if items are found but nr is specified and not found, raises ItemNotFoundError. Optionally excludes disabled items. get_item_attrs(name, by_label=False, nr=None) Return dictionary of HTML attributes for a single ListControl item. The HTML element types that describe list items are: OPTION for SELECT controls, INPUT for the rest. These elements have HTML attributes that you may occasionally want to know about – for example, the “alt” HTML attribute gives a text string describing the item (graphical browsers usually display this as a tooltip). The returned dictionary maps HTML attribute names to values. The names and values are taken from the original HTML. get_item_disabled(name, by_label=False, nr=None) Get disabled state of named list item in a ListControl. get_items(name=None, label=None, id=None, exclude_disabled=False) Return matching items by name or label. For argument docs, see the docstring for .get() get_value_by_label() Return the value of the control as given by normalized labels. pairs() Return list of (key, value) pairs suitable for passing to urlencode. possible_items(by_label=False) Deprecated: return the names or labels of all possible items. Includes disabled items, which may be misleading for some use cases. set(selected, name, by_label=False, nr=None) Deprecated: given a name or label and optional disambiguating index nr, set the matching item’s selection to the bool value of selected. Selecting items follows the behavior described in the docstring of the ‘get’ method. if the item is disabled, or this control is disabled or readonly, raise AttributeError. set_all_items_disabled(disabled) Set disabled state of all list items in a ListControl. Parameters:disabled – boolean disabled state set_item_disabled(disabled, name, by_label=False, nr=None) Set disabled state of named list item in a ListControl. Parameters:disabled – boolean disabled state set_single(selected, by_label=None) Deprecated: set the selection of the single item in this control. Raises ItemCountError if the control does not contain only one item. by_label argument is ignored, and included only for backwards compatibility. set_value_by_label(value) Set the value of control by item labels. value is expected to be an iterable of strings that are substrings of the item labels that should be selected. Before substring matching is performed, the original label text is whitespace-compressed (consecutive whitespace characters are converted to a single space character) and leading and trailing whitespace is stripped. Ambiguous labels: it will not complain as long as all ambiguous labels share the same item name (e.g. OPTION value). toggle(name, by_label=False, nr=None) Deprecated: given a name or label and optional disambiguating index nr, toggle the matching item’s selection. Selecting items follows the behavior described in the docstring of the ‘get’ method. if the item is disabled, or this control is disabled or readonly, raise AttributeError. toggle_single(by_label=None) Deprecated: toggle the selection of the single item in this control. Raises ItemCountError if the control does not contain only one item. by_label argument is ignored, and included only for backwards compatibility. class mechanize.SelectControl(type, name, attrs, select_default=False, index=None)[source] Bases: mechanize._form_controls.ListControl Covers: SELECT (and OPTION) OPTION ‘values’, in HTML parlance, are Item ‘names’ in mechanize parlance. SELECT control values and labels are subject to some messy defaulting rules. For example, if the HTML representation of the control is: <SELECT name=year> <OPTION value=0 label="2002">current year</OPTION> <OPTION value=1>2001</OPTION> <OPTION>2000</OPTION> </SELECT> The items, in order, have labels “2002”, “2001” and “2000”, whereas their names (the OPTION values) are “0”, “1” and “2000” respectively. Note that the value of the last OPTION in this example defaults to its contents, as specified by RFC 1866, as do the labels of the second and third OPTIONs. The OPTION labels are sometimes more meaningful than the OPTION values, which can make for more maintainable code. Additional read-only public attribute: attrs The attrs attribute is a dictionary of the original HTML attributes of the SELECT element. Other ListControls do not have this attribute, because in other cases the control as a whole does not correspond to any single HTML element. control.get(…).attrs may be used as usual to get at the HTML attributes of the HTML elements corresponding to individual list items (for SELECT controls, these are OPTION elements). Another special case is that the Item.attrs dictionaries have a special key “contents” which does not correspond to any real HTML attribute, but rather contains the contents of the OPTION element: <OPTION>this bit</OPTION> get(name=None, label=None, id=None, nr=None, exclude_disabled=False) Return item by name or label, disambiguating if necessary with nr. All arguments must be passed by name, with the exception of ‘name’, which may be used as a positional argument. If name is specified, then the item must have the indicated name. If label is specified, then the item must have a label whose whitespace-compressed, stripped, text substring-matches the indicated label string (e.g. label=”please choose” will match ” Do please choose an item “). If id is specified, then the item must have the indicated id. nr is an optional 0-based index of the items matching the query. If nr is the default None value and more than item is found, raises AmbiguityError. If no item is found, or if items are found but nr is specified and not found, raises ItemNotFoundError. Optionally excludes disabled items. get_item_attrs(name, by_label=False, nr=None) Return dictionary of HTML attributes for a single ListControl item. The HTML element types that describe list items are: OPTION for SELECT controls, INPUT for the rest. These elements have HTML attributes that you may occasionally want to know about – for example, the “alt” HTML attribute gives a text string describing the item (graphical browsers usually display this as a tooltip). The returned dictionary maps HTML attribute names to values. The names and values are taken from the original HTML. get_item_disabled(name, by_label=False, nr=None) Get disabled state of named list item in a ListControl. get_items(name=None, label=None, id=None, exclude_disabled=False) Return matching items by name or label. For argument docs, see the docstring for .get() get_labels() Return all labels (Label instances) for this control. If the control was surrounded by a <label> tag, that will be the first label; all other labels, connected by ‘for’ and ‘id’, are in the order that appear in the HTML. get_value_by_label() Return the value of the control as given by normalized labels. pairs() Return list of (key, value) pairs suitable for passing to urlencode. possible_items(by_label=False) Deprecated: return the names or labels of all possible items. Includes disabled items, which may be misleading for some use cases. set(selected, name, by_label=False, nr=None) Deprecated: given a name or label and optional disambiguating index nr, set the matching item’s selection to the bool value of selected. Selecting items follows the behavior described in the docstring of the ‘get’ method. if the item is disabled, or this control is disabled or readonly, raise AttributeError. set_all_items_disabled(disabled) Set disabled state of all list items in a ListControl. Parameters:disabled – boolean disabled state set_item_disabled(disabled, name, by_label=False, nr=None) Set disabled state of named list item in a ListControl. Parameters:disabled – boolean disabled state set_single(selected, by_label=None) Deprecated: set the selection of the single item in this control. Raises ItemCountError if the control does not contain only one item. by_label argument is ignored, and included only for backwards compatibility. set_value_by_label(value) Set the value of control by item labels. value is expected to be an iterable of strings that are substrings of the item labels that should be selected. Before substring matching is performed, the original label text is whitespace-compressed (consecutive whitespace characters are converted to a single space character) and leading and trailing whitespace is stripped. Ambiguous labels: it will not complain as long as all ambiguous labels share the same item name (e.g. OPTION value). toggle(name, by_label=False, nr=None) Deprecated: given a name or label and optional disambiguating index nr, toggle the matching item’s selection. Selecting items follows the behavior described in the docstring of the ‘get’ method. if the item is disabled, or this control is disabled or readonly, raise AttributeError. toggle_single(by_label=None) Deprecated: toggle the selection of the single item in this control. Raises ItemCountError if the control does not contain only one item. by_label argument is ignored, and included only for backwards compatibility. class mechanize.SubmitControl(type, name, attrs, index=None)[source] Covers: INPUT/SUBMIT BUTTON/SUBMIT Members: Inherited-members:   Show-inheritance:   class mechanize.ImageControl(type, name, attrs, index=None)[source] Bases: mechanize._form_controls.SubmitControl Covers: INPUT/IMAGE Coordinates are specified using one of the HTMLForm.click* methods. get_labels() Return all labels (Label instances) for this control. If the control was surrounded by a <label> tag, that will be the first label; all other labels, connected by ‘for’ and ‘id’, are in the order that appear in the HTML. pairs() Return list of (key, value) pairs suitable for passing to urlencode.
__label__pos
0.733458
FED实验室 - 专注WEB端开发和用户体验 谈谈Javascript中的throttle and debounce 点滴Javascript 煦涵 3325℃ 0评论 一、应用场景 在日常开发中,我们会经常遇到以下连续事件、频率控制及其造成的性能优化等问题: 1、鼠标事件:mousemove(拖曳)/mouseover(划过)/mouseWheel(滚屏) 2、键盘事件:keypress(基于ajax的用户名唯一性校验)/keyup(文本输入检验、自动完成)/keydown(游戏中的射击) 3、window的resize/scroll事件(DOM元素动态定位) 如果事件回调中包含很多处理程序、ajax请求和DOM操作,频繁的触发将是非常耗时和耗性能的,有时还会导致浏览器崩溃的问题。 如何解决上述问题,有两种方法:throttle(节流)和debounce(去抖) throttle:连续的时间间隔(每隔一定时间间隔执行callback)。 debounce:空闲的时间间隔(callback执行完,过一定空闲时间间隔再执行callback)。 二、实现原理(resize事件为例) 有各需求缩放浏览器窗口时,实现页面宽高随窗口自适应。我们可能会像下面这样做: var $win = $(window), setSize = function() { var winW = $win.width(), winH = $win.height(); $("#wrapper").css({ width: winW, height: winH }); }; setSize(); //绑定事件 $win.on("resize", function(event){ setTimeout(setSize, 1000); }); 但是我们这里有个问题,每次执行完定时器没有被清除,同时增加延迟参数,下面我们来封装一个函数: var $win = $(window), throttle = function(fn, delay) { var timer = null; return function() { var context = this, args = arguments; if(timer) { clearTimeout(timer); } timer = setTimeout(function() { fn.apply(context, args); }, delay); } }, setSize = function() { var winW = $win.width(), winH = $win.height(); $("#wrapper").css({ width: winW, height: winH }); }; setSize(); //绑定事件 $win.on("resize", throttle(function(event) { setSize(); }, 1000)); 封装的throttle函数带有两个参数,一个fn执行函数,一个延迟时间间隔。上例中每隔1秒执行一次setSize()。 三、常见库的封装 现在比较流行的库实现的throttle和debounce的有: Underscore.js by Jeremy Ashkenas Lodash.js by John-David Dalton jQuery Plugin by Ben Alman 以上三种实现方式中: 1、jQuery Plugin中的实现,详细描述,请参考文章jQuery throttle / debounce: Sometimes, less is more! 2、Underscore.js和Lodash.js实现方式不同,但是函数参数基本相同; 3、关于debounce,分析Underscore.js中的源码: /** * [debounce description] * @param {[type]} func [回调函数] * @param {[type]} wait [等待时长] * @param {[type]} immediate [是否立即执行] * @return {[type]} [description] */ _.debounce = function(func, wait, immediate) { var timeout, args, context, timestamp, result; var later = function() { var last = _.now() - timestamp; //小于wait时间,继续延迟wait-last执行later,知道last >= wait才执行func if (last < wait && last > 0) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) { result = func.apply(context, args); if (!timeout) context = args = null; } } }; return function() { context = this; args = arguments; timestamp = _.now(); //是否立即执行 var callNow = immediate && !timeout; if (!timeout) timeout = setTimeout(later, wait); if (callNow) { result = func.apply(context, args); context = args = null; } return result; }; }; 综合以上应用情景中的情景1、3肯定是用throttle,情景2 throttle和debounce可以按需使用。 四、参考链接 Debounce and Throttle: a visual explanation Throttling function calls Underscore.js throttle vs debounce example - JSFiddle jquery.ba-throttle-debounce.js Simple Throttle Function 以上就是本文的描述,感谢您的阅读,文中不妥之处还望批评指正。 下面是「FED实验室」的微信公众号二维码,欢迎扫描关注: FED实验室 行文不易,如有帮助,欢迎打赏! 赞赏支持or喜欢 (2)or分享 (0) 捐赠共勉 发表我的评论 取消评论 表情 Hi,您需要填写昵称和邮箱! • 昵称 (必填) • 邮箱 (必填) • 网址
__label__pos
0.953012
Jump to content Casio91Fin Member • Content Count 140 • Joined • Last visited • Medals Everything posted by Casio91Fin 1. Hey. Does anyone have an Inventory weight script. The only thing I've found is this, but I don't get it to work 2. Does anyone have this "Infantry Occupy House" script and possibly added "JBOY UP & Down" to it? command forms, however, would be like this what I was looking for [Group this, Postion X, radius] ...... simple if possible 3. Casio91Fin player inventory weight script When a player opens their own inventory then somewhere in the corner of the inventory would show how much stuff the player is carrying "Kg" 4. Casio91Fin Need Occupation script @Fr3eMan thanks for that but it wasn't quite what i was looking for. 5. The purpose should be to find the "TRANSMITTER" tower on the map and create a task from it. (23 pieces Altis) and of course to choose randomly. nearestTerrainObjects 6. Casio91Fin Find object in map thx @Harzach 7. How could I make this work? _AI_Leader = New_AI_Group createUnit [JalkavakiJohtajat select floor (random count JalkavakiJohtajat), _AI_Spawn_Pos, [], 0, "NONE"]; if (_AI_Leader == "I_officer_F") then {_AI_Leader setRank "LIEUTENANT"; [_AI_Leader, "LIEUTENANT"] call BIS_fnc_setUnitInsignia;}; else they are. _AI_Leader setRank "SERGEANT"; [_AI_Leader, "SERGEANT"] call BIS_fnc_setUnitInsignia; 8. Casio91Fin add Insignia to AI i figured out what was the problem if (typeOf _AI_Leader == "I_officer_F") then {_AI_Leader setRank "LIEUTENANT"; [_AI_Leader, "LIEUTENANT"] call BIS_fnc_setUnitInsignia;} else {_AI_Leader setRank "SERGEANT"; [_AI_Leader, "SERGEANT"] call BIS_fnc_setUnitInsignia;}; 9. Is it possible for the AI team to randomly select their own mission? I'm feeling like a terribly long to write the script, because the AI group is created, however, in many cases again. What I’m looking for here AI randomly chooses a task for himself. a list of possibilities for what the AI could do 1. [New_AI_Group_3, _pos_1, 500] call lambs_wp_fnc_taskPatrol; 2.[New_AI_Group_3, _pos_1, 50] call lambs_wp_fnc_taskCamp; 3.[New_AI_Group_3, _pos_1, 50] call lambs_wp_fnc_taskGarrison; 4.[New_AI_Group_3, _pos_1, 50] spawn lambs_wp_fnc_taskCQB; 5.[New_AI_Group_3, _pos_1] call BIS_fnc_taskDefend; 6.[New_AI_Group_3, _pos_1, 1000] call BIS_fnc_taskPatrol; //Jalkaväki for "_x" from 0 to (1 * Multiplier) do { New_AI_Group_3 = createGroup [independent, true]; _AI_Spawn_Pos = [_Pos_1, 40, 160, 10 + random 15, 0, 20, 0] call BIS_fnc_findSafePos; _AI_Leader = New_AI_Group_3 createUnit [JalkavakiJohtajat select floor (random count JalkavakiJohtajat), _AI_Spawn_Pos, [], 0, "NONE"]; _AI_Leader setRank "SERGEANT"; [_AI_Leader, "SERGEANT"] call BIS_fnc_setUnitInsignia; _AI_Leader allowFleeing 0; _AI_Leader setSkill (0.75 + random 0.25); _AI_Leader enableAIFeature ["AUTOTARGET", false]; _AI_Leader enableAIFeature ["RADIOPROTOCOL", true]; _AI_Leader enableAIFeature ["COVER", true]; _AI_Leader enableAIFeature ["PATH", true]; sleep 2; for "_x" from 0 to (2 + (floor random 2 + 3 * Multiplier)) do { _NewAI = New_AI_Group_3 createUnit [JalkavakiSotilaat select floor (random count JalkavakiSotilaat), _AI_Spawn_Pos, [], 0 ,"NONE"]; _AINewRank = selectRandom ["PRIVATE","PRIVATE","PRIVATE","CORPORAL"]; _NewAI setRank _AINewRank; [_NewAI, _AINewRank] call BIS_fnc_setUnitInsignia; _NewAI allowFleeing 0; _NewAI setSkill (0.45 + random 0.55); _NewAI enableAIFeature ["AUTOTARGET", false]; _NewAI enableAIFeature ["RADIOPROTOCOL", true]; _NewAI enableAIFeature ["PATH", true]; _NewAI enableAIFeature ["SUPPRESSION", true]; }; sleep .5; New_AI_Group_3 setBehaviour "AWARE"; New_AI_Group_3 setCombatMode "RED"; [New_AI_Group_3, _pos_1, random 100 + 150] spawn lambs_wp_fnc_taskCQB; }; 10. Casio91Fin Random task for AI @UnDeaD. i am going to test and yes @mr_centipede is right it must be 6. Thank you, the script is working very well 11. Casio91Fin Help with Custom Loadout I don't know if this helps. _magazinePrimary = getArray (configFile >> "CfgWeapons" >> _weaponPrimary >> "magazines"); to _magazinePrimary = getArray (configFile / "CfgWeapons" / _weaponPrimary / "magazines"); Fixed [_x, (selectRandom [ "arifle_MX_F","arifle_Katiba_F","srifle_DMR_01_F","SMG_01_F","arifle_MX_khk_F","arifle_AK12_F","arifle_AKM_F","srifle_DMR_07_blk_F","LMG_Mk200_F","LMG_Zafir_F"]),3] call BIS_fnc_addWeapon; 12. My coop idea is how players would get fire support for their missions. If there are more than 3 players in a player group then group leader could get a fire support command. (Radio commands 1. artillery, 2. air support, 3.missile attack and something else ) Is it possible to do? 13. @pierremgi I'm going to test today - Works well. I tested with artificial intelligence and it works flawlessly. 14. Hi. How should the Defense module be done correctly so that it works properly? I’ve watched videos and read, but I can’t get it to work. And somewhere I’ve read that it doesn’t work anymore is this claim true? If anyone could make it work and tell me how to make it work. 15. Really good work. Is it possible for the earth to be a map and not the soil material? 16. i think is best option: I don’t want infantry to swim in the ocean, but for some reason some spawn in the ocean. (better explained) 17. Can you fix few thing and add? 1. Enemies do not spawn in the water, applies to all inf, light veh, heavy veh, static weapon. 2. light vehicles would also have infantry. (80% chance that there is an infantry ride) 18. Casio91Fin Names of different cities 😎 Works like a dream 19. Hey Question? how to make these three work so that there is no need to swap places with each other. _TownName = text nearestLocation [_Mission_Pos, "NameVillage"]; <<-------/NameCity / NameCityCapital / NameVillage [west, [localize "STR_CAS_Mission_Name_4", "Suomi Painaa Tehtävät"], [format [localize "STR_CAS_Mission_Text_4", _TownName], localize "STR_CAS_Mission_Name_4", ""], _Mission_Pos, true, 1, true, "danger", true] call BIS_fnc_taskCreate; [localize "STR_CAS_Mission_Name_4", "ASSIGNED", true] spawn BIS_fnc_taskSetState; SP_Mission_Pos_Residential = 20. Casio91Fin Names of different cities now did not give an error, but also no name 21. Casio91Fin Names of different cities _TownName = text (nearestLocations [_MissionPos, ["NameCity", "NameCityCapital", "NameVillage"], 200] #0); = "Any"? mission text ------------- (00007FF7B08441D0) ------------------- - -- - - - -- - 22. Casio91Fin Names of different cities I do not get to work, even though I am very close to its success 23. Casio91Fin Names of different cities Thanks for this, but it only gives me the coordinates. No village or city names. _TownName = nearestLocations [_Mission_Pos, ["NameCity", "NameCityCapital", "NameVillage"], 200]; //had to delete "text" when an error message was received why? mission text ......... ..... ..... ...... ([location namecity at 9188, 15948] = Agios Dionysios ) .................. 24. Hey. When I tried to try this arma 3 I got the message "Error when loading the scenario!" can you fix this? demo mission 25. How to add the prize if a player kills 10 AIs and the player gets one respawn ticket. I already have this kind of floor plan initServer.sqf: addMissionEventHandler ["EntityKilled", { params ["_killed", "_killer", "_instigator"]; if ((_killed isKindOf "Man") and (!isPlayer _killed)) then { [_killer, 100] call HALs_money_fnc_addFunds; removeAllWeapons _killed; removeAllItems _killed; removeAllAssignedItems _killed; deleteVehicle (nearestObject [_killed, "WeaponHolderSimulated"]); }; }]; ×
__label__pos
0.72321
Composite Multi-layers to Single Layer Hi Guys, I am looking for a way to composite several drawing layers into one drawing layer for further editing later. I also want to save the multi layers I have since editing them would be easier than having to fix anything with the composite layer. any ideas on the best method to accomplish this? Not sure if I understand right but if you are trying to merge multiple vector images into new vector images you can do this in the Network view. - You need to make sure all the layers are vector (not bitmap images or effects on them). - you plug them into a Composite that you set to As Vector - finally set the Write module to output in TVG format. This will create a sequence of TVG (vector files) images in the Frames folder of the scene. Then you can import them in any scene you want. You would still have your individual layers and these new merged images. Steve you are a saint! This is exactly what I needed to know, thanks for the assistance. cheers, 14g
__label__pos
0.792292
How to Highlight Birthday Automatically In this article, you will see how you can change the color when a Birthday is coming up in few days. No macro has been used. Step 1: Add the current date First of all, add the current date with the function TODAY() in a new column. =TODAY() Step 2: Gap for the months In a new column, calculate the number of months remaining before the birthday. Use the DATEDIF function and the parameter "ym" (number of months in the current year). =DATEDIF(C2;D2;"ym") Step 3: Gap for the days In the same way, we are going to calculate the number of days remaining before the birthday. Use the function DATEDIF again but with the value"md" this time for the third argument. =DATEDIF(C2;D2;"md") Step 4: Analyze of the result As you can see on the picture • If the birthday is soon, the value of the gap in day and month is huge • On the other hand, if the birthday has been reached, both value are close to 0 In this situation, it is not easy to create a test to warning when a birthday is coming up. Except if you add a delay 😉😋💡 Step 5: Add a delay Write the number of days before a birthday in another cell and change the previous formula to include this value. The formula for the months becomes =DATEDIF(C2-$I$2;D2;"ym") The formula for the days becomes =DATEDIF(C2-$I$2 ;D2;"md") Write the reference of the delay with an absolute reference, for example, $I$2. Step 6: Create a test with the 2 columns The test for the month is really easy because the value must be 0 =E2=0 The test for the days is not complex but it is clever. We will test if the Gap in days is lower than or equal to the Delay in days. The test is: =F2<=$I$2 Merge these 2 tests into a single one with the logical operator AND. =AND(E2=0,F2<=$I$2) The test returns what we expect but it isn't really easy to identify which cells return TRUE at first glance. This is why we are going to write this test in a conditional formatting rule. Step 7: Add a conditional formatting • First copy the formula of the test (with the AND) • Open the menu Home > Conditional Formatting > New rule • Select the option Use a formula to determine which cells to format • Paste the formula • Customize the format when the rule is TRUE (here font color: white and background: red) Step 8: Change the range of application The final step is to apply this conditional formatting to the whole column. • Open the menu Home > Conditional Formatting > Manage rules • In the text box Apply to, select the range of cells to apply the conditional formatting to. The final result is displayed below: Related posts Permanent link to this article: https://www.excel-exercise.com/how-to-highlight-birthday-automatically/ Leave a Reply Your email address will not be published.
__label__pos
0.670599
This topic describes commonly used terms in Log Service to help you better understand and use Log Service. Region A region is a service node of Alibaba Cloud. By deploying services in different Alibaba Cloud regions, you can get your services closer to your customers, achieving lower access latency and a better user experience. Currently, Alibaba Cloud provides multiple regions throughout China. Project A project is a basic management unit in Log Service and is used to isolate and control resources. You can use a project to manage all the logs and related log sources of an application. Logstore A Logstore is a unit in Log Service to collect, store, and consume logs. Each Logstore belongs to one project, and each project can have multiple Logstores. You can create multiple Logstores for a project as needed. Typically, an independent Logstore is created for each type of logs of an application. For example, you have a game application big-game, and three types of logs exist on the server: operation_log, application_log, and access_log. In this case, you can create a project named big-game and then create three Logstores in this project to collect, store, and consume the three types of logs respectively. Log A log is the minimum data unit processed in Log Service. Log Service uses a semi-structured data mode to define a log. The specific data model is as follows: • Topic: a user-defined field used to mark multiple logs. For example, access logs can be marked based on the sites. By default, this field is an empty string, which is also a valid topic. • Time: a reserved field in the log, which is used to indicate the log generation time (the number of seconds since 1970-1-1 00:00:00 UTC). Generally, this field is generated directly based on the time in the log. • Content: a field used to record the specific log content. The content consists of one or more content items. Each content item is a key-value pair. • Source: a field used to indicate the source of a log. For example, this field indicates the IP address of the host where the log is generated. This field is empty by default. Log Service has different requirements on the values of different fields, as described in the following table. Table 1. Log fields Field Requirement time An integer in the standard UNIX timestamp format, in seconds. topic A UTF-8 encoded string up to 128 bytes in length. source A UTF-8 encoded string up to 128 bytes in length. content One or more key-value pairs. A key is a UTF-8 encoded string up to 128 bytes in length. It can contain only letters, underscores (_), and digits and cannot start with a digit. A value is a UTF-8 encoded string up to 1024 × 1024 bytes in length. tags Tags appear in alphabetical order. The key and value of each tag are strings. Note The key in the content field cannot use any of the following keywords: __time__, __source__, __topic__, __partition_time__, _extract_others_, and __extract_others__. Topic Logs in one Logstore can be grouped by log topics. You can specify the topic when writing a log. For example, you can use your ID as the log topic when writing logs. If you do not need to group logs in a Logstore, specify the same log topic for all of the logs. Note By default, the log topic is an empty string, which is also a valid topic. Various log formats are used in actual scenarios. The following example shows how to map a raw NGINX access log to the log data model of Log Service. Assume that the IP address of your NGINX server is 10.10.10.1. A raw log on this server is as follows: 10.1.1.1 - - [01/Mar/2012:16:12:07 +0800] "GET /Send? AccessKeyId=82251054** HTTP/1.1" 200 5 "-" "Mozilla/5.0 (X11; Linux i686 on x86_64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2" Map the raw log to the log data model of Log Service, as described in the following table. Table 2. Log data model of Log Service Field Content Description topic "" Use the default value (empty string). time 1330589527 The precise time when the log is generated, in seconds. The time is converted from the timestamp of the raw log. source "10.10.10.1" Use the IP address of the server as the log source. content Key-value pair The specific content of the log. You can decide how to extract the raw log content and combine the extracted content into key-value pairs, as described in the following table. Table 3. Custom key-value pairs Key Value ip "10.1.1.1" method "GET" status "200" length "5" ref_url "-" browser "Mozilla/5.0 (X11; Linux i686 on x86_64; rv:10.0.2) Gecko/20100101 Firef" Logs A collection of multiple logs. Log group A group of logs. LogGroupList A collection of log groups used to return results. Encoding method The following table lists the content encoding method that the system currently supports. More encoding methods will be available in the future. The supported encoding methods are specified in the Content-Type field in the RESTful API. Table 4. Supported encoding method Definition Content-Type Protobuf The data model is encoded by Protobuf. application/x-protobuf For more information about the Protobuf format, see Data encoding method. Note Protobuf does not require the key-value pair to be unique. However, you cannot use the same key. Otherwise, the behavior is undefined. Protobuf must follow the order of field number to encode fields in one message. Otherwise, data may fail to be parsed.
__label__pos
0.520873
AWS CloudFormation User Guide (API Version 2010-05-15) AWS::CodeDeploy::DeploymentConfig The AWS::CodeDeploy::DeploymentConfig resource creates a set of deployment rules, deployment success conditions, and deployment failure conditions that CodeDeploy uses during a deployment. The deployment configuration specifies, through the use of a MinimumHealthyHosts value, the number or percentage of instances that must remain available at any time during a deployment. Syntax To declare this entity in your AWS CloudFormation template, use the following syntax: JSON { "Type" : "AWS::CodeDeploy::DeploymentConfig", "Properties" : { "DeploymentConfigName" : String, "MinimumHealthyHosts" : MinimumHealthyHosts } } YAML Type: AWS::CodeDeploy::DeploymentConfig Properties: DeploymentConfigName: String MinimumHealthyHosts: MinimumHealthyHosts Properties DeploymentConfigName A name for the deployment configuration. If you don't specify a name, AWS CloudFormation generates a unique physical ID and uses that ID for the deployment configuration name. For more information, see Name Type. Important If you specify a name, you cannot perform updates that require replacement of this resource. You can perform updates that require no or some interruption. If you must replace the resource, specify a new name. Required: No Type: String Update requires: Replacement MinimumHealthyHosts The minimum number of healthy instances that must be available at any time during an CodeDeploy deployment. For example, for a fleet of nine instances, if you specify a minimum of six healthy instances, CodeDeploy deploys your application up to three instances at a time so that you always have six healthy instances. The deployment succeeds if your application successfully deploys to six or more instances; otherwise, the deployment fails. For more information about instance health, see CodeDeploy Instance Health in the AWS CodeDeploy User Guide. Required: Yes Type: CodeDeploy DeploymentConfig MinimumHealthyHosts Update requires: Replacement Return Value Ref When you pass the logical ID of an AWS::CodeDeploy::DeploymentConfig resource to the intrinsic Ref function, the function returns the deployment configuration name, such as mydeploymentconfig-a123d0d1. For more information about using the Ref function, see Ref. Example The following example requires at least 75% of the fleet to be healthy. For example, if you had a fleet of four instances, the deployment proceeds one instance at a time. JSON "TwentyFivePercentAtATime" : { "Type" : "AWS::CodeDeploy::DeploymentConfig", "Properties" : { "MinimumHealthyHosts" : { "Type" : "FLEET_PERCENT", "Value" : "75" } } } YAML TwentyFivePercentAtATime: Type: AWS::CodeDeploy::DeploymentConfig Properties: MinimumHealthyHosts: Type: "FLEET_PERCENT" Value: 75
__label__pos
0.621761
Take the 2-minute tour × Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required. Just tried googling but couldn't find any example, but how 3 % 5 = 3 Googled it share|improve this question 6   If you count $1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,\ldots$, what is the third number that comes up? –  Michael Greinecker Sep 12 '12 at 10:30 5   When you divide $3$ by $5$, the remainder is $3$. –  Joe Johnson 126 Sep 12 '12 at 10:31 2   Also, $3 \equiv 3 \mod 5$, because $3-3=0 \equiv 0 \mod 5$. –  Andrea Orta Sep 12 '12 at 10:34 1   If you are asking this question $\implies$ you need to look at the definition of modulo operation. see en.wikipedia.org/wiki/Modulo_operation –  Aang Sep 12 '12 at 12:45 6 Answers 6 up vote 10 down vote accepted If $a$ and $b$ are positive integers, there exist unique integers $q$, $r$ with $$a = bq + r$$ and $0 \leq r < b$. This theorem is called the division algorithm, and $a\ \%\ b$ is defined to be this $r$. In your case, $3 = 0\cdot5 + 3$ and $0 \leq 3 < 5$, so the answer is 3. share|improve this answer $a \equiv b \, (\text{mod} c)$ means $a-b$ is divisible by $c$. [Definition] Since $3 - 3 = 0$ is divisible by $5$, we have $3 \equiv 3 \, (\text{mod} 5)$. share|improve this answer hmmm Actually Mod (%) returns the remainder Given two positive numbers, a (the dividend) and b (the divisor), a modulus % is the remainder of the Euclidean division of a by b. For instance, the expression "9 mod 8" would evaluate to 1 because 9divided by 8 leaves a remainder of 1, while "9 mod 3" would evaluate to 0 because the division of 9 by 3 leaves a remainder of 0. hope this will help you cheers share|improve this answer      plus if your dividend if less than the divisor, then your remainder will be the dividend :) –  Ali Sep 12 '12 at 10:52      It works for negative numbers too, unless you are using a non-standard definition on Mod? –  user1729 Sep 12 '12 at 13:02 a modulo b = r Where r is the remainder of the division a by b => a = b*q + r where q is the quotient of the division a/b. For example: 9 modulo 4 = 1 and the quotient is 2 i.e 9 = (4*2) + 1 In a similar fashion: 3 modulo 5 = 3 and the quotient is 0- =>3=(5*0)+3 share|improve this answer by definition, the remainder of a division is the fractional part of a division. if you have 3/5 (3 divided by 5), you have the fractional part represented as 3/5. since a remainder is the dividend or numerator of a fraction, you just take 3 as your remainder (the divisor or denominator is not mentioned in the remainder). therefore, 3 % 5 = 3. just like 5 % 3 = dividing 5 by 3, you get 1 and 2/5. to get the remainder part, you know that 2 is the numerator so 2 is the remainder (the denominator, 5, is not mentioned in the remainder). share|improve this answer in general if a is less than b then a%b= a so this implies that 3%5=3 and 6%7=6. another way of viewing this is by reading the statement a%b as "how many object remains if we SUCCESSIVELY take "b" objects from a bag with "a" objects untill we CAN'T TAKE ANYMORE!". Having that in mind 5%2 mean that we successively take 2 objects from a bag containing 5 objects. 1st we will take the 2 objects and leaving behind 3 objects, then we take another 2 object leaving behing 1 object in the bag, since we can't take 2 objects any more, SINCE there is only one remaining hence 5%2=1. applying the same analogy and solving for 3%5 we initially have 3 object in a bag and we want to successively take 5 objects. but we cant since the are insufficient objects in the bag so we can't take any objects and hence 3 objects will remain, this implies that 3%5=3. hope this helps. share|improve this answer      Check out the following link to help format questions/answers. –  Vincent Oct 21 '14 at 16:13 Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.949023
[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index] qemu KVM: can't boot a qemu machine with liveCD (system rescue) Hi, there is no special forum/mailinglist existing for qemu-KVM, right? My problem is: I can't boot a qemu machine with liveCD (system rescue) I inserted <os> <type arch='x86_64' machine='pc-0.12'>hvm</type> <boot dev='cdrom'/> <boot dev='hd'/> <bootmenu enable='yes'/> </os> into xml-File but the appearing menu at boot time: Press F12 for boot menu. (I pressed F12) Select boot device: 1. Legacy option rom 2. Legacy option rom (indeed, same line two times) 3. CD-ROM [ata1-0: QEMU DVD-ROM ATAPI-4 CD-Rom/DVD-Rom] 4. virtio-net.zrom 5.4.4. (GPL) ether But 3. is NOT booting from CD! 1. and 2. not either. But grub is booting with 3. CD-ROM is ignored. Why? Using sr0 instead of cdrom results in: root@squeeze64:~# virsh start suse111 error: failed to get domain 'suse111' error: Domain not found: no domain with matching name 'suse111' BTW: I did /etc/init.d/libvirt-bin stop -> start before, of course. Mount of /dev/sr0 or /dev/cdrom to /mnt works, the CD is present and is readable. How can I boot a qemu machine with liveCD (system rescue)? Why? -> because of kernel panic Please help! Are there other possibilities to boot a qemu-KVM machine by a liveCD? thx Ekkard Reply to:
__label__pos
0.868815
1.15.1.1 What is a WSGI application? The WSGI PEP can be quite confusing if all you want to do is write applications quickly and easily. The best way to explain the WSGI is to work through an example demonstrating how an application written as a CGI script has to be modified to work as a WSGI application. Consider the CGI script code below: #!/usr/bin/env python print 'Content-type: text/plain\n\n' print 'Hello world!' This does nothing more than print the words 'Hello world!' to a web browser in plain text. What we have done is sent an HTTP header Content-type: text/plain\n\n and then a text string to the browser. The webserver may also have sent a '200 OK' response if the application didn't crash. To create the same result using a WSGI application we would use this code: def application(environ, start_response): start_response('200 OK', [('Content-type','text/plain')]) return ['Hello world!'] WSGI servers are configured to look for an object with a particular name, usually application, and call it, passing the application callable a dictionary named environ containing environmental variables and also a function named start_response which must be called before the application returns a value. Our callable named application is our WSGI application. You could name it differently if your WSGI server had a different naming convention. You may not be happy with the function start_response being passed as a parameter to our application callable. Whilst this is not possible in some other languages it is perfectly legitimate in Python. This ability to pass callables as function parameters is crucial to understanding how the WSGI works. Here is an example to consider: def b(text): print text def a(print_response): print_response("Hello World!") return "It worked!" print a(b) In this case we are passing the function b to the a as the parameter print_response. We are then printing the value returned from a. What do you think the result will be? The answer is this: Hello World! It worked! Make sure you understand this example before you read on. A WSGI application must do two things, these are: 1. Call the start_response function (passed to our application callable) with the parameters status and headers in the correct order. This will set the status of the application and send the HTTP headers. In our example the status is '200 OK' meaning everything has gone according to plan and we only send one header, the Content-type header with the value text/plain. 2. Return an iterable containing nothing but strings. In this example the iterable is simply a list containing one string. The return value could equally well have been ['Hello', ' ', 'world!'] but there was no need to make things more complicated. There are some big advantages in rewriting our code as a WSGI application:
__label__pos
0.989083
Take the 2-minute tour × TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required. The following is the code related to my title page: \documentclass[a4paper,12pt]{book} \usepackage{amsmath, amsthm, amssymb} \usepackage{url} \usepackage[algoruled,vlined]{algorithm2e} \usepackage{graphicx,subfigure} % for nice tables \usepackage{booktabs} % end for nice tables % for using color names \usepackage[usenames,dvipsnames]{color} % end for using color names % for nicer figure captions \usepackage[font=small,format=plain,labelfont=bf,up,textfont=it,up]{caption} % end for nicer figure captions % fancy headers and footers \usepackage{fancyhdr} \pagestyle{fancy} \renewcommand{\headrulewidth}{0.1pt} % for upper line \renewcommand{\footrulewidth}{0.1pt} % for lower line \fancyhead[LE,RO]{\itshape \nouppercase \rightmark} \fancyhead[LO,RE]{\itshape \nouppercase \leftmark} \fancyfoot[C]{\thepage} \usepackage{colortbl} % for multirow option in the tables \usepackage{multirow} \usepackage[semicolon]{natbib} \usepackage{fancybox} \usepackage{xcolor} \usepackage{framed} \newcommand{\HRule}{\rule{\linewidth}{0.5mm}} \newenvironment{myfancybox}{% \def\FrameCommand{\fboxsep=\FrameSep \fcolorbox{black}}% \color{black}\MakeFramed {\FrameRestore}}% {\endMakeFramed} %\bibliographystyle{plain} %Choose a bibliograhpic style \usepackage{sectsty} \allsectionsfont{\itshape} % for height of the heading \setlength{\headheight}{15pt} \parskip1ex \begin{document} \begin{titlepage} \quad \vspace{2cm} \quad \begin{center} {\fontsize{70}{70}\selectfont \textbf{ Word1\\ %\vspace{2mm} Word Word\\ \vspace{2mm} Word Word Word} } {\large text text text text text text text text text text text text text text text text text text text text text text text text text text text text} \end{center} \pagestyle{plain} \end{titlepage} \end{document} The problem is that my title has 'Word 1' quite separated from the second row. Another problem is that the whole text is actually not centered. I my preview it is shifted to the left. How could I adjust the title page to have proper title and with the centered text? My intention is to have the title page close to this: http://algo2.iti.kit.edu/documents/DementievDiss.pdf I would appreciate help on how to achieve such a title page. share|improve this question 2   Please, make the code snippet into a MWE: without knowing the class you're using it's difficult to give a sensible answer. –  egreg Jun 15 '12 at 10:27      @egreg I edited my question. Please write a comment on how to easily copy/paste the code from my .tex file such that it is display as with 4 white spaces at this website. –  boy Jun 15 '12 at 10:48      Please use a more describing title. "Problem with title page" can fit 100 different questions. –  Martin Scharrer Jun 15 '12 at 10:49 2   @boy: Not on tex.sx ;) -- a question here should be exactly one problem, one distinct issue. This way, the posts are supposed to be maximally helpful for other users looking for help. That's why we require a certain degree of abstraction in questions. –  doncherry Jun 15 '12 at 11:29 1   regarding why there is more space after "word 1", you have wrapped that block in a group, so the baselines will revert to the "outside" value when the group closes unless the group ends with a blank line or \par. the baselineskip appropriate for the type size inside the group will be applied between the first and second lines since the second line ends with `\` forcing the setting. –  barbara beeton Jun 15 '12 at 12:26 1 Answer 1 up vote 2 down vote accepted It's a bit hard to do it with standard LaTeX commands, so some low level TeX can come handy. \documentclass[a4paper,12pt]{book} \usepackage{graphicx,array} \begin{document} \begin{titlepage} \hrule height0pt % fix a starting point \vskip 0pt minus 1000pt % back up how much it's needed \raggedright % no indentation \hspace*{\dimexpr(\paperwidth-\textwidth)/2 - \oddsidemargin - 1in - \hoffset\relax}% shift to center \hbox to 0pt{% make a zero width box \vbox to \textheight{\centering % this is the main part %%% \vspace*{\fill} \hrule \vspace{1.5cm} \textsc{Brutus C. Dull} \vspace{1.5cm} {\Large\bfseries Applied Tetrapiloctomy\\ for GPS Systems\par} \vspace{1cm} \hrule \vspace{\stretch{5}} \parbox{2.5cm}{ \raisebox{-.5\height}{\includegraphics[width=2.5cm]{example-image-1x1}}} \hfill \parbox{\dimexpr\textwidth-3.5cm\relax}{ \raggedright\large\sffamily Dissertation zur Erlangung des Grades des Doktors der Ingenieurwissenschaften (Dr.-Ing.) der Naturwissenschaftlich-Technischen Fakult\"aten der Universit\"at des Saarlandes\par \medskip \hrule \medskip \hspace*{\fill}Saarbr\"ucken, 2006\par }\par }%end of \vbox \hss}%end of \hbox \vskip 0pt minus 1000pt % some space for accommodating the whole thing \hrule height0pt % fix an end point \end{titlepage} \end{document} share|improve this answer Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.999513
Updated locallang-XML files with most recent translations. [Packages/TYPO3.CMS.git] / typo3 / alt_mod_frameset.php 1 <?php 2 /*************************************************************** 3 * Copyright notice 4 * 5 * (c) 1999-2004 Kasper Skaarhoj ([email protected]) 6 * All rights reserved 7 * 8 * This script is part of the TYPO3 project. The TYPO3 project is 9 * free software; you can redistribute it and/or modify 10 * it under the terms of the GNU General Public License as published by 11 * the Free Software Foundation; either version 2 of the License, or 12 * (at your option) any later version. 13 * 14 * The GNU General Public License can be found at 15 * http://www.gnu.org/copyleft/gpl.html. 16 * A copy is found in the textfile GPL.txt and important notices to the license 17 * from the author is found in LICENSE.txt distributed with these scripts. 18 * 19 * 20 * This script is distributed in the hope that it will be useful, 21 * but WITHOUT ANY WARRANTY; without even the implied warranty of 22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 23 * GNU General Public License for more details. 24 * 25 * This copyright notice MUST APPEAR in all copies of the script! 26 ***************************************************************/ 27 /** 28 * Creates the frameset for 'Frameset modules' like Web>* and File>* 29 * 30 * $Id$ 31 * Revised for TYPO3 3.6 2/2003 by Kasper Skaarhoj 32 * XHTML compliant content (with exception of a few attributes for the <frameset> tags) 33 * 34 * @author Kasper Skaarhoj <[email protected]> 35 */ 36 /** 37 * [CLASS/FUNCTION INDEX of SCRIPT] 38 * 39 * 40 * 41 * 63: class SC_alt_mod_frameset 42 * 88: function main() 43 * 150: function printContent() 44 * 45 * TOTAL FUNCTIONS: 2 46 * (This index is automatically created/updated by the extension "extdeveval") 47 * 48 */ 49 50 require ('init.php'); 51 require ('template.php'); 52 53 54 55 56 /** 57 * Script Class for rendering the frameset which keeps the navigation and list frames together for socalled "Frameset modules" 58 * 59 * @author Kasper Skaarhoj <[email protected]> 60 * @package TYPO3 61 * @subpackage core 62 */ 63 class SC_alt_mod_frameset { 64 65 // Internal, static: 66 var $defaultWidth = 245; // Default width of the navigation frame. Can be overridden from $TBE_STYLES['dims']['navFrameWidth'] (alternative default value) AND from User TSconfig 67 var $resizable = TRUE; // If true, the frame can be resized. 68 69 // Internal, dynamic: 70 var $content; // Content accumulation. 71 72 // GPvars: 73 var $exScript=''; // Script to load in list frame. 74 var $id=''; // ID of page 75 var $fW=''; // Framewidth 76 77 78 79 80 81 82 83 /** 84 * Creates the header and frameset for the module/submodules 85 * 86 * @return void 87 */ 88 function main() { 89 global $BE_USER,$TBE_TEMPLATE,$TBE_STYLES; 90 91 // GPvars: 92 $this->exScript = t3lib_div::_GP('exScript'); 93 $this->id = t3lib_div::_GP('id'); 94 $this->fW = t3lib_div::_GP('fW'); 95 96 // Setting resizing flag: 97 $this->resizable = $BE_USER->uc['navFrameResizable'] ? TRUE : FALSE; 98 99 // Setting frame width: 100 if (intval($this->fW) && $this->resizable) { // Framewidth from stored value, last one. 101 $width = t3lib_div::intInRange($this->fW,100,1000)+10; // +10 to compensate for width of scrollbar. However, width is always INSIDE scrollbars, so potentially it will jump a little forth/back... 102 } else { // Framewidth from configuration; 103 $width = $BE_USER->uc['navFrameWidth']; 104 $width = intval($width)?intval($width):($TBE_STYLES['dims']['navFrameWidth'] ? intval($TBE_STYLES['dims']['navFrameWidth']) : $this->defaultWidth); 105 } 106 107 // Navigation frame URL: 108 $script = t3lib_div::_GP('script'); 109 $nav = t3lib_div::_GP('nav'); 110 $URL_nav = htmlspecialchars($nav.'?currentSubScript='.rawurlencode($script)); 111 112 // List frame URL: 113 $URL_list = htmlspecialchars($this->exScript?$this->exScript:($script.($this->id?'?id='.rawurlencode($this->id):''))); 114 115 // Start page output 116 $TBE_TEMPLATE->docType='xhtml_frames'; 117 $this->content = $TBE_TEMPLATE->startPage('Frameset'); 118 119 // THis onload handler is a bug-fix for a possible bug in Safari browser for Mac. Posted by Jack COLE. Should not influence other browsers negatively. 120 $onLoadHandler = ' onload="if(top.content.nav_frame.location.href.length == 1) {top.content.nav_frame.location=\''.$URL_nav.'\';};"'; 121 122 if ($this->resizable) { 123 $this->content.= ' 124 <frameset cols="'.$width.',*"'.$onLoadHandler.'> 125 <frame name="nav_frame" src="'.$URL_nav.'" marginwidth="0" marginheight="0" scrolling="auto" /> 126 <frame name="list_frame" src="'.$URL_list.'" marginwidth="0" marginheight="0" scrolling="auto" /> 127 </frameset> 128 129 </html> 130 '; 131 } else { 132 $this->content.= ' 133 134 <frameset cols="'.$width.',8,*" framespacing="0" frameborder="0" border="0"'.$onLoadHandler.'> 135 <frame name="nav_frame" src="'.$URL_nav.'" marginwidth="0" marginheight="0" frameborder="0" scrolling="auto" noresize="noresize" /> 136 <frame name="border_frame" src="border.html" marginwidth="0" marginheight="0" frameborder="0" scrolling="no" noresize="noresize" /> 137 <frame name="list_frame" src="'.$URL_list.'" marginwidth="0" marginheight="0" frameborder="0" scrolling="auto" noresize="noresize" /> 138 </frameset> 139 140 </html> 141 '; 142 } 143 } 144 145 /** 146 * Outputting the accumulated content to screen 147 * 148 * @return void 149 */ 150 function printContent() { 151 echo $this->content; 152 } 153 } 154 155 // Include extension? 156 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['typo3/alt_mod_frameset.php']) { 157 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['typo3/alt_mod_frameset.php']); 158 } 159 160 161 162 163 164 165 166 167 168 169 170 // ****************************** 171 // Starting document output 172 // ****************************** 173 174 // Make instance: 175 $SOBE = t3lib_div::makeInstance('SC_alt_mod_frameset'); 176 $SOBE->main(); 177 $SOBE->printContent(); 178 ?>
__label__pos
0.985038
Export (0) Print Expand All Collapse the table of content Expand the table of content Expand Minimize sp_help_notification (Transact-SQL) Reports a list of alerts for a given operator or a list of operators for a given alert. Topic link iconTransact-SQL Syntax Conventions sp_help_notification [ @object_type= ] 'object_type', [ @name= ] 'name', [ @enum_type= ] 'enum_type', [ @notification_method = ] notification_method [ , [ @target_name = ] 'target_name' ] [ @object_type =] 'object_type' The type of information to be returned. object_typeis char(9), with no default. object_type can be ALERTS, which lists the alerts assigned to the supplied operator name, or OPERATORS, which lists the operators responsible for the supplied alert name. [ @name =] 'name' An operator name (if object_type is OPERATORS) or an alert name (if object_type is ALERTS). name is sysname, with no default. [ @enum_type =] 'enum_type' The object_typeinformation that is returned. enum_type is ACTUAL in most cases. enum_typeis char(10), with no default, and can be one of these values. Value Description ACTUAL Lists only the object_types associated with name. ALL Lists all theobject_types including those that are not associated with name. TARGET Lists only the object_types matching the supplied target_name, regardless of association withname. [ @notification_method =] notification_method A numeric value that determines the notification method columns to return. notification_method is tinyint, and can be one of the following values. Value Description 1 E-mail: returns only the use_email column. 2 Pager: returns only the use_pager column. 4 NetSend: returns only the use_netsend column. 7 All: returns all columns. [ @target_name =] 'target_name' An alert name to search for (if object_type is ALERTS) or an operator name to search for (if object_type is OPERATORS). target_name is needed only if enum_type is TARGET. target_name is sysname, with a default of NULL. 0 (success) or 1 (failure) If object_type is ALERTS, the result set lists all the alerts for a given operator. Column name Data type Description alert_id int Alert identifier number. alert_name sysname Alert name. use_email int E-mail is used to notify the operator: 1 = Yes 0 = No use_pager int Pager is used to notify operator: 1 = Yes 0 = No use_netsend int Network pop-up is used to notify the operator: 1 = Yes 0 = No has_email int Number of e-mail notifications sent for this alert. has_pager int Number of pager notifications sent for this alert. has_netsend int Number of net send notifications sent for this alert. If object_type is OPERATORS, the result set lists all the operators for a given alert. Column name Data type Description operator_id int Operator identification number. operator_name sysname Operator name. use_email int E-mail is used to send notification of the operator: 1 = Yes 0 = No use_pager int Pager is used to send notification of the operator: 1 = Yes 0 = No use_netsend int Is a network pop-up used to notify the operator: 1 = Yes 0 = No has_email int Operator has an e-mail address: 1 = Yes 0 = No has_pager int Operator has a pager address: 1 = Yes 0 = No has_netsend int Operator has net send notification configured. 1 = Yes 0 = No This stored procedure must be run from the msdb database. To execute this stored procedure, a user must be a member of the sysadmin fixed server role. A. Listing alerts for a specific operator The following example returns all alerts for which the operator François Ajenstat receives any kind of notification. USE msdb ; GO EXEC dbo.sp_help_notification @object_type = N'ALERTS', @name = N'François Ajenstat', @enum_type = N'ACTUAL', @notification_method = 7 ; GO B. Listing operators for a specific alert The following example returns all operators who receive any kind of notification for the Test Alert alert. USE msdb ; GO EXEC sp_help_notification @object_type = N'OPERATORS', @name = N'Test Alert', @enum_type = N'ACTUAL', @notification_method = 7 ; GO Was this page helpful? (1500 characters remaining) Thank you for your feedback Community Additions ADD Show: © 2015 Microsoft
__label__pos
0.619162
ad-1.1.0: Automatic Differentiation PortabilityGHC only Stabilityexperimental [email protected] Numeric.AD.Internal.Forward Description Unsafe and often partial combinators intended for internal usage. Handle with care. Documentation bundle :: a -> a -> AD Forward aSource unbundle :: AD Forward a -> (a, a)Source apply :: Num a => (AD Forward a -> b) -> a -> bSource bind :: (Traversable f, Num a) => (f (AD Forward a) -> b) -> f a -> f bSource bind' :: (Traversable f, Num a) => (f (AD Forward a) -> b) -> f a -> (b, f b)Source bindWith :: (Traversable f, Num a) => (a -> b -> c) -> (f (AD Forward a) -> b) -> f a -> f cSource bindWith' :: (Traversable f, Num a) => (a -> b -> c) -> (f (AD Forward a) -> b) -> f a -> (b, f c)Source transposeWith :: (Functor f, Foldable f, Traversable g) => (b -> f a -> c) -> f (g a) -> g b -> g cSource
__label__pos
0.516232
Take the 2-minute tour × Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required. The common use case here is a user uploading a jpeg logo with a white/color background. It's (fairly) simple to switch the white pixels to transparent ones, but this leaves aliasing artifacts. An ideal solution would essentially "undo" the aliasing (given a known background color). At a minimum, the solution must beat the bg_removal script for ImageMagick (http://imagemagick.org/Usage/scripts/bg_removal). share|improve this question 1   I'm not sure what you are referring to as "aliasing artifacts". Maybe you could include a small image to demonstrate. –  nobar Feb 17 '11 at 3:22 4   The aliasing he is refering comes from the fact that, especially at boundary of an object, the color of the pixel is a mixture of the background and the object's color. –  Ken Wayne VanderLinde Feb 17 '11 at 3:31      @nobar: (anti-)aliasing artefacts is something very common. Seen the OP's question and the fact that he mentions ImageMagick and the fact that you don't know what aliasing artefacts are, I doubt you'll be able to help him ;) GIYF –  SyntaxT3rr0r Feb 27 '11 at 1:08      @SyntaxT3rr0r: You made my day. LOL –  nobar Feb 27 '11 at 4:49 add comment 2 Answers The "Color to Alpha" algorithm in GIMP looks like it does a pretty good job. The source is GPL and can be found here. A demonstration of what the GIMP algorithm does with something like a logo is here, and the GIMP manual page for Color-to-Alpha is here. It looks like the most straightforward way to do this programmatically would be to use GIMP batch mode. share|improve this answer      Initial testing looks impressive, check out the before and after for a very tough test case: As JPG with white bg --> As PNG with transparent bg –  Jeremy Lewis Feb 17 '11 at 7:05      Wow, that is a tough case. The letters have become semi-transparent, but at least the anti-aliasing looks good! –  nobar Feb 17 '11 at 8:23      I've added an additional step of "doubling" the remaining image to help get rid of the letter transparency, I'll post the full GIMP Python script + how to execute it shortly. Thanks for starting me in the right direction. –  Jeremy Lewis Feb 18 '11 at 0:58 add comment up vote 1 down vote accepted As promised, here's a working solution for the common white --> alpha use case. This is running on an Ubuntu 10.04.1 LTS server with the standard GIMP installation (2.6.8). from gimpfu import * def run(input_filepath): image = pdb.gimp_file_load(input_filepath, input_filepath) image.disable_undo() layer = image.active_layer if not layer.is_rgb: pdb.gimp_image_convert_rgb(image) white = gimpcolor.RGB(1.0, 1.0, 1.0, 1.0) bg_color = pdb.gimp_image_pick_color(image, layer, 0, 0, True, False, 0) if bg_color == white: pdb.plug_in_colortoalpha(image, layer, bg_color) layer_copy = layer.copy() image.add_layer(layer_copy) image.merge_visible_layers(CLIP_TO_IMAGE) pdb.file_png_save_defaults(image, image.active_layer, input_filepath, input_filepath) run('%(input_filepath)s') I execute this code from Python (within Django) using the subprocess module (code_as_string is the above code as a string, with input_filepath inserted: gimp_args = (settings.PATH_TO_GIMP, '-i', '--batch-interpreter=python-fu-eval', '-b', code_as_string, '-b', 'from gimpfu import pdb; pdb.gimp_quit(True)') environ = os.environ.copy() environ['GIMP2_DIRECTORY'] = settings.PATH_TO_GIMP_DIR p = subprocess.Popen(gimp_args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=environ) rc = p.wait() if rc: logging.error(p.stdout.read()) share|improve this answer add comment Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.581032
AddOn Studio Wiki Advertisement XML UI ← XML properties < Layers Layers holds a list of Layer elements, and is a fundamental UI building block for creating visible graphical elements for Frame UI elements. Layers can be defined on any Frame type elements, including Buttons and EditBoxes. Inheritance[] Inherited by: none, Inherits: none, Defined in: Frame Elements[] <Layer> ... Attributes[] none Summary[] Layers are the primary 'Drawing' mechanism in the WoW UI, and allow WoW to display all of its visible UI elements on the screen. Layers work by defining a list of <Layer> elements, each of which define a 'Z order' level, and define which LayoutFrames should be drawn at that 'level'. A layer works by listing Texture and FontString elements each of which can draw itself based on how its defined. The cumulative effect of all the Layers in the Layer list, combined with their FontString and Texture elements, will render the all the visible elements for a Frame at runtime. Example[] <Frame name="MyFrame"> <Layers> <Layer> <Texture> <Size x="100" y="100" /> <HitRectInsets> <AbsInset left="0" right="-100" top="0" bottom="0"/> </HitRectInsets> <Color a="1" r="1" g="1" b="1" /> </Texture> <Texture> <Size x="100" y="100" /> <Color a="1" r="1" g="1" b="1" /> </Texture> </Layer> </Layers> </Frame> This example will show a frame with several textures. Details[] Advertisement
__label__pos
0.565395
Check sibling questions Suppose the ratio of money I & Sanjay have is 1 : 3. What percentage to total money do I have, & what percentage does Sanjay have?   Given ratio is 1 : 3   So, 1 part I have, 3 Parts Sanjay has Total parts = 1 + 3  = 4   So, 15.jpg   Suppose the ratio of Mangoes, Apples and Oranges I have is 2 : 1 : 1. How much percent mangoes, apples, Oranges do I have?   Given ratio is 2 : 1 : 1   So, There are 2 parts of mangoes, 1 part of Apples & 1 part of oranges. Total parts = 2 + 1 + 1 = 4 Ratios to percentage - Part 2       Transcript I have 1 out of 4 parts Percentage I have = 1/4 × 100 = 100/4 % = 25% Sanjay has 3 out of 4 parts Percentage Sanjay have = 3/4 × 100 = 3 × 100/4 % = 3 × 25% Mangoes 2 out of 4 parts Percentage = 2/4 × 100% = 1/2 × 100% = 50% Apples 1 out of 4 parts Percentage = 1/4 × 100% = 1/2 × 100% = 25% Oranges 1 out of 4 parts Percentage = 1/4 × 100% = 1/2 × 100% = 25% Davneet Singh's photo - Teacher, Engineer, Marketer Made by Davneet Singh Davneet Singh is a graduate from Indian Institute of Technology, Kanpur. He has been teaching from the past 12 years. He provides courses for Maths and Science at Teachoo.
__label__pos
0.995132
• ONLY x = 1 is a solution of the original equation! x = -2 cannot be a solution, because you can't take logs of negative numbers, so if you try to put x = -2 into the original logarithmic equation you would get . log 2 (-2 + 1) +log 2 (-2) = 1. Neither logarithm makes sense, so -2 can't be a solution. • Do you see the similarity between what happened now and what happened when we solved for a spherically symmetric solution to the wave equation? If there were really no charges or currents at the origin, there would not be spherical outgoing waves. The spherical waves must, of course, be produced by sources at the origin. • Figure 63: Solution of Poisson's equation in two dimensions with simple Dirichlet boundary conditions in the -direction.The solution is plotted versus at .The dotted curve (obscured) shows the analytic solution, whereas the open triangles show the finite difference solution for . • A system of equations refers to a number of equations with an equal number of variables. We will only look at the case of two linear equations in two unknowns. The situation gets much more complex as... • Solving Equations We begin with the basics, that is solving simple equations. The most impor-tant thing to remember when solving equations is that whatever you do to one side you need to also do to the other. We will use letters x, yand zto denote the things that we want to nd out. Take an example. Let xbe the cost of a meal in a particular ... • Many students assume that all equations have solutions. This article will use three examples to show that assumption is incorrect. Given the equation 5x - 2 + 3x = 3(x+4)-1 to solve, we will collect our like terms on the left hand side of the equal sign and distribute the 3 on the right hand side of the equal sign. 5x ... • No matter how many steps are in the original equation, you can work backwards and apply the inverse operations, in order, to arrive at the solution! You can solve two-step inequalities in exactly the same way. Just work backwards, using the inverse operations, to arrive at the solution. • Thus as a congruence this equation has a solution mod m for any m. That there is no Z-solution follows from Q(sqrt(-51)) having class number 2, which is rel. prime to 3, by the same kind of method used to find the Z-solutions to y^2 = x^3-2. $\endgroup$ – KConrad Nov 28 '10 at 7:19 Speed queen coin box key The following system of equations has no solution. \(\begin{array}{l} x-y=-2\\ \\x-y=1\end{array}\) How would you know? One way would be to try and solve the system, and see that you get an untrue statement. Another would be to realize that the first equation is saying that x–y is one number, while the second equation is saying that x–y has a different value. These can’t both be true. Absolute Value Equations. Follow these steps to solve an absolute value equality which contains one absolute value: Isolate the absolute value on one side of the equation. Is the number on the other side of the equation negative? If you answered yes, then the equation has no solution. If you answered no, then go on to step 3. Wood burning stove clearance sale A system of two linear equations has no solution. The first equation is 3 x + y = −5. Select the second equation that would make this system have no solution. Sometimes equations have no solution. This means that no matter what value is plugged in for the variable, you will ALWAYS get a contradiction. Watch this tutorial and learn what it takes for an equation to have no solution. Hippie fonts on google docs How to know if an equation has Infinitely Many Solutions or No Solution? We look at these 2 special cases in this free math video tutorial by Mario's Math Tu... 2 days ago · As Example:, 8x 2 + 5x – 10 = 0 is a quadratic equation. Root of quadratic equation: Root of a quadratic equation ax 2 + bx + c = 0, is defined as real number α, if aα 2 + bα + c = 0. The zeroes of the quadratic polynomial and the roots of the quadratic equation ax 2 + bx + c = 0 are the same. Solution of a Quadratic Equation by different ...
__label__pos
0.981941
Back to all articles August 23, 2023 - 8 minutes Beyond Coding: Essential Skills for Tech Professionals You have the basic required skills for your field, but what else should you learn? Ironhack - Changing The Future of Tech Education All Courses You’ve learned your programming language of choice and you’re done, right?! You’ve learned everything you need to know to land your dream tech job, right?! Unfortunately, it’s not that simple–there are lots of other skills tech professionals need to know, both hard and soft, to ensure they’re ready to take on the challenge.  Before we dive right into the crucial skills that you should have as a tech professional beyond those that you already have, let’s explore why it’s so important to learn other skills to land your dream role in tech.  Why is it Important to Learn Other Skills in Tech? Programmers should be aware of cybersecurity threats in addition to their coding knowledge and UX/UI designers should know how to analyze the data that they see from their users to optimize their designs. But beyond the skills listed on a job description lie others that are essential. Why? Here you go:  • Tech moves at an incredibly fast pace: tech moves fast; we’re sure you already know that. To keep up with new technologies or innovations, it’s crucial that you’re constantly researching what’s happening in the industry and staying up-to-date with new advancements.  • Additional skills make you a more valuable candidate: if you just have the basic skills required to be a cybersecurity professional, you’ll find that your application is sitting next to a large pile of candidates with the exact same skills. Branching out and widening your skill set separates your application and makes employers more likely to hire you.  • You’ll be better suited to move into a different role: as we mentioned, tech moves fast and let’s be realistic: it’s possible that your job becomes unnecessary or filled by someone else with knowledge of newer tools and technologies. But if you boast a wide range of skills, employers are more likely to move you into a new role or choose to upskill or reskill you.  We’ll dive into a more detailed summary of skills to learn for specific roles later on, but first, let’s cover some of the main tech skills that all techies should have in their toolbox.  Important tech skills for all techies No matter if you’re the world’s best UX/UI designer or Python programmer, all tech professionals should be able to put these skills on their resume:  1. General computer skills: we’re sure you know how to type, but are you proficient at using both Macs and PCs? Or various processing systems? Today, everyone is expected to have some computer knowledge because our world is so digitally-focused, but showing how comfortable you are with various softwares and machines helps instill a sense of confidence in your manager.  2. Artificial intelligence: AI is all the rage right now and it’s only going to continue growing in popularity, with more and more AI-skilled professionals needed. If you can work on your AI skills outside the office and add it to your resume, hiring managers will definitely take note.  3. Marketing: knowing how to create your product is just one step; you have to know how to market it as well. Reviewing some key marketing knowledge such as search engine optimization and content marketing can help you take your skills to the next level.  4. Coding: listen, we’re not saying you need to become a hackathon champion if your goal is to become a data analyst. But it could be helpful to have some coding knowledge so you can handle little problems on your own or even identify what an issue is.  5. Data analytics: data is behind every single decision we make and knowing how to read, sort, and visualize data can help you make better decisions in every part of your life and especially at work. You don’t need to be the world’s fastest data analyzer, but learning how to understand important figures at a basic level could help your actions become more effective.  6. Web design: you could write some fantastic code but choose a design that just doesn’t resonate with your user and suddenly no one is checking out your website. Knowing the basics of quality user design can help you incorporate that into your project from the back-end. Now that you know why it’s important to learn other skills outside your direct responsibilities, let’s cover some key skills for each of these four sectors: web development, UX/UI design, data analytics, and cybersecurity. Other Skills to Learn in Web Development  Web developers boast knowledge in programming languages, frameworks, cording, and testing, but what else could be valuable? Let’s discuss:  • Familiarity with the user experience: at the end of the day, web developers are creating a product for a certain user and if the web design doesn’t meet user needs and expectations, it’s entirely useless. To ensure that designs are created for the user, web developers should understand the entire user experience, which will help them create a better product.  • Attention to detail: writing lines and lines of code can be tedious and seemingly endless, but a small mistake could make the entire site come crashing down. Web developers that can prove their attention to detail skills will reassure potential employers and be more attractive candidates.  • Teamwork: web developers tend to work on large teams with back-end developers, front-end developers, product managers, UX designers, team leads, and more and the last thing managers want is a developer who can’t play nice with others. Show off your teamwork skills and give examples of how you’ve worked on large and diverse teams before if you want to truly impress your prospective employer.  • Good communication: developers have a reputation for sitting at their computers all day and writing lines and lines of code and, well, there’s a reason for that. Similarly to the need for good teamwork skills, developers should expect to spend lots of time explaining what they’re doing to others and need to be able to communicate properly with the entire team.  Other Skills to Learn in UX/UI Design To create the perfect design, UX/UI designers are proficient in interaction design, information architecture, prototyping, and design, in addition to these sometimes forgotten gems:  • Familiarity with the differences between mobile and desktops: the perfect design might exist solely on a mobile browser and when you bring it to a desktop it doesn’t work at all. Knowing the slight differences between mobile and desktop browsers such as loading time, page layout, and accessibility can help bring your design to an entirely new audience–and bring more business.  • Visualization skills: for some, it can be hard to picture what a final product will look like and we get it–how could anyone picture something that doesn’t exist yet?! But even though it’s challenging, successful UX/UI designers boast the ability to anticipate how a design will look, choosing the right elements right from the beginning and adjusting them as needed throughout the design process.  • Familiarity with testing procedures: the design process can be long and tedious and ultimately depends heavily on how testing goes and how users respond to the design. UX/UI designers who have experience with or knowledge about testing procedures can anticipate problems before they arise and quickly solve any found issues.  • Good listening skills: just like with developing a website, the success of a design ultimately lies with one thing: if the user reacts positively to it. Showing a potential employer that you’re ready to listen and incorporate all kinds of feedback into your design will be well-received.  Other Skills to Learn in Data Analytics In addition to typical data analytic skills like machine learning, data visualization, data cleaning, and analysis, data analysts can spruce up their resumes with the following skills:  • Programming languages: you might equate programming languages with web development and coding, but programming languages like R and Python can analyze large quantities of data efficiently and quickly, allowing you to focus on other tasks that require human brainpower.  • Presentation skills: spoiler alert: your findings are practically useless if you can’t communicate them to your team, sharing what you’ve learned and your recommendations for the future. Knowing how to visualize your results can make all the difference between a good data analyst and an incredible data analyst.  • Writing skills: data analysts are frequently tasked with creating reports of their findings to share with colleagues or stakeholders; knowing how to not only put that information into charts but also write it well can be quite the challenge for those with weak writing skills.  • Problem solving skills: from incomplete datasets to tight deadlines, data analysts face lots of problems and need to be prepared to handle said issues professionally and properly, ensuring they’re completing their responsibilities to the best of their abilities.  Other Skills to Learn in Cybersecurity  Cybersecurity professionals might think all employers are looking for is Cloud knowledge and network security skills, but to become a truly competitive candidate, we recommend becoming familiar with:  • Attention to detail: scams or phishing attempts can seem really real sometimes and it’s easy to fall for one if you’re not paying full attention. Highlighting your ability to double and triple check every detail will reassure potential employers. • Critical thinking: some threats require a lot of creativity and critical thinking to find the right solution; knowing how to think outside the box and come up with innovative solutions is highly valuable. • Coding: lots of protections put into place by cybersecurity professionals are embedded into a website’s code; if you have basic knowledge of some of the most common programming languages, you’ll be able to implement these protections yourself and check for updates or problems later on.  • Artificial intelligence: the rise of artificial intelligence has led to more realistic phishing and malware attacks. Cyber professionals who can identify computer-generated scams will become increasingly relevant in the coming years. It may seem like a lot of skills to learn, but that’s exactly why Ironhack was born: to take talented individuals and make them into the next generation of techies, ready to fill market gaps in different areas of the sector. Bootcamp graduates are incredibly valuable because of just that; they use their diverse backgrounds and their newly acquired technical knowledge to create a new kind of tech professional If you’re thinking about changing careers, there’s never been a better time to dive right into tech and we’d love to guide you along your journey in tech. What are you waiting for? Check out our courses and apply today.  Related Articles Recommended for you Ready to join? More than 10,000 career changers and entrepreneurs launched their careers in the tech industry with Ironhack's bootcamps. Start your new career journey, and join the tech revolution!
__label__pos
0.631149
Eufy Smart Lock Touch & Wi-Fi Aviso: *privacidade não incluída neste produto Eufy Smart Lock Touch & Wi-Fi Data da avaliação: 9 de Novembro de 2022 | A Mozilla investigou por 8 horas | Opinião da Mozilla | Votos das pessoas: Não é assustador To unlock Eufy's Smart Lock Touch & WiFi, all you have to do is give it the finger and use your fingerprint. Or open your door from far away with WiFi. Or use your Bluetooth connected phone to unlock the door when you're within 30 feet or so. You can also use the built-in keypad. Or even, gasp!, a physical key. So many ways to open your door! Wonder if saying, "Open Sesame" works too? O que pode acontecer se algo der errado? Smart locks are one of those connected devices that seem to worry lots of people. The pros: They offer a lot of convenience with multiple ways to unlock the door to your home, a way to track who comes and goes from your home, they can allow you give out a keypad number to people like a babysitter and then revoke that when they no longer need access, and they can help you make sure you locked your front door when your anxiety kicks in on vacation. The cons: They can be vulnerable to any number of things such as power outages, lost or compromised phones, ransomware attacks on the company who made your lock, product security vulnerabilities, WiFi and/or Bluetooth vulnerabilities, home hub vulnerabilities, bad software updates, data leaks, and more. With all that said, how does Eufy’s Smart Lock Touch & WiFi stack up? This lock operates over WiFi and can be controlled from just about anywhere with the Eufy Security app. It also uses a fingerprint, which also seems generally safe, especially as Eufy stores your fingerprint data locally on the device rather than on the internet in the cloud where it could be more vulnerable. There's also a keypad and a key to unlock it. So, lots of ways to unlock this lock, if you need. We found no known security breaches of this smart lock. Unfortunately, Eufy has had some significant security vulnerabilities with their security cameras. In June 2022, security experts foundthree security vulnerabilities in Eufy's Homebase 2 video storage and management device that could have allowed hackers to take control of the hub, control it remotely, or steal video footage. Eufy/Anker developed fixes for these security vulnerabilities and released them to users in a timely manner. And in May 2021, Eufy was forced to apologize for a bug that exposed the camera feeds of 712 users to strangers. Eufy said the glitch happened during a software update and “users were able to access video feeds from other users’ cameras.” Eufy said in a statement the glitch was fixed an hour after it was discovered. So, the bad news is, Eufy’s security cameras have had some serious security issues. The good news is, Eufy as a company seems to have stepped up and immediately fixed these bugs and to get the updates out to their users quickly. While these security oopsies happened to their video cameras, not their smart locks, it’s a good reminder that software updates can go wrong, which wouldn’t be good for your smart lock. On the privacy front, Eufy’s privacy policy says they can collect a good deal of personal information on you -- things like name, email, gender, birth date, location, device information, and more. And while Eufy says they don’t sell your personal information -- which is good -- they say they can use that information to show you ads from them and third party advertisers, which isn’t so good (but also pretty standard on the internet these days). They also say they can collect personal information on you from third parties who provide it to them, such as law enforcement authorities. This worries us a bit because the way that line in their privacy policy is written is rather vague and seems like it could leave open the possibility they could collect information on users from a variety of third parties, for example, data brokers. What’s the worst that could happen? Well, it is a smart lock that can be unlocked with your fingerprint ID. We've watched enough movies to know there's always a chance someone could chop your finger off and use it to get in your home. We really hope that never happens to you. We also hope Eufy keeps tight security on their Eufy Security app so no one can hack it and unlock your home from far away. That would be bad. Dicas para se proteger • Check out tips to ensure your smart lock safety • Maintain a strong door • Choose a secure access code • Set up two-factor authentication • Do not sign up with third-party accounts. Better just log in with email and strong password. • Chose a strong password! You may use a password control tool like 1Password, KeePass etc • Use your device privacy controls to limit access to your personal information via app (do not give access to your camera, microphone, images, location unless neccessary) • Keep your app regularly updated • Limit ad tracking via your device (eg on iPhone go to Privacy -> Advertising -> Limit ad tracking) and biggest ad networks (for Google, go to Google account and turn off ad personalization) • Request your data be deleted once you stop using the app. Simply deleting an app from your device usually does not erase your personal data. • When starting a sign-up, do not agree to tracking of your data if possible. • mobile Pode me bisbilhotar? informações Câmera Dispositivo: Não Aplicativo: Não Microfone Dispositivo: Não Aplicativo: Não Rastreia localização Dispositivo: Não Aplicativo: Sim O que pode ser usado para se inscrever? Que dados a empresa coleta? Como a empresa usa esses dados? We ding this product for sharing personal data for advertisement and for combining users' data with data from third parties. Eufy does not sell data. However, they share personal identifiers for advertisement purposes: "We do not Sell any personal information to third parties. In particular, we do not Sell the personal information of minors under 16 years of age. In the preceding 12 months, we have disclosed the following categories of personal information to the following categories of recipients: [...] Advertising networks, data analytics providers. - Personal Identifiers." Eufy also combine users' data with data obtained from third parties: "We collect or obtain Personal Data from third parties who provide it to us (e.g., credit reference agencies; law enforcement authorities; etc.)." Como você pode controlar seus dados? We ding this product because it is not clear all users have the same rights to access and delete their data. Eufy specifically mentions the right to delete data only for users based in California. "Subject to applicable law, you may have the following rights regarding the Processing of your Relevant Personal Data...." Data retention policies for Eufy are rather confusing, however Eufy does promise to delete or anonymised data once they do not need it any more: "Once the periods in paragraphs (1), (2) and (3) above, each to the extent applicable, have concluded, we will either: - permanently delete or destroy the relevant Personal Data; or - anonymize the relevant Personal Data." Qual é o histórico conhecido da empresa na proteção de dados dos usuários? Médio In June 2022, three security vulnerabilities were found in Eufy's Homebase 2 video storage and management device that could have allowed hackers to take control of the hub, control it remotely, or steal video footage. Eufy/Anker developed fixes for these secruity vulnerabilities and released them to users in a timely manner. In May 2021, Eufy was forced to apologize for a bug that exposed the camera feeds of 712 users to strangers. Eufy said the glitch happened during a software update and “users were able to access video feeds from other users’ cameras.” Eufy said in a statement the glitch was fixed an hour after it was discovered. Informações de privacidade infantil Our Sites, products, or services are not directed to children under the age of 13. As a result, our Sites, products, or services do not request or knowingly collect personal information from individuals under the age of 13. If you are not 13 or older, you should not visit or use our Sites, products, or services . Este produto pode ser usado offline? Sim Informações de privacidade fáceis de entender? Sim Structured and concise Links para informações de privacidade Este produto atende aos nossos padrões mínimos de segurança? informações Sim Criptografia Sim Senha forte Sim Atualizações de segurança Sim Gerencia vulnerabilidades Sim Política de privacidade Sim O produto usa inteligência artificial? informações Sim Esta inteligência artificial não é confiável? Não foi possível determinar Que tipo de decisões a inteligência artificial faz sobre você ou por você? The built-in AI reduces the number of false alerts you receive by intelligently differentiating people from objects. It has features like pet detection, and even crying detection. A empresa é transparente sobre como funciona a inteligência artificial? Não foi possível determinar O usuário tem controle sobre os recursos da inteligência artificial? Sim *privacidade não incluída Mergulhe mais fundo Comentários Tem um comentário a fazer? Nos diga.
__label__pos
0.771132
var animationTime = 150; var Dorado = { DivHeight:0, InitSquares: function(divId){ jQuery("div#" + divId + " img").each(function(){ var img = jQuery(this); var alt = img.attr("alt"); var title = ""; var text = ""; if(alt.indexOf(";")!=-1) { title = alt.split(";")[0]; text = alt.split(";")[1]; } else { text = alt; } var newDiv = jQuery(" ").addClass("imageInfo"); var bgDiv = jQuery(" ").addClass("bg"); newDiv.append(bgDiv); var textDiv = jQuery(" ").html("" + title + " " + text); textDiv.css("line-height", "normal"); newDiv.append(textDiv); var par = img.parent(); while(!par.is("div")) par = par.parent(); par.css({"position":"relative","overflow":"hidden"}).prepend(newDiv); Dorado.DivHeight = newDiv.height()+parseInt(newDiv.css("padding-top"))+parseInt(newDiv.css("padding-bottom")); newDiv.css("bottom",-Dorado.DivHeight); par.mouseenter(function(){ var div = jQuery(this).find("div.imageInfo"); div.animate({"bottom":0},animationTime); }); par.mouseleave(function(){ var div = jQuery(this).find("div.imageInfo"); div.animate({"bottom":-Dorado.DivHeight},animationTime); }); }); } } jQuery(document).ready(function(){ Dorado.InitSquares("svid94_24ea01c113069e1881180005447"); });
__label__pos
0.99421
Navigating Through The Underground Internet We live in an era of free-flowing data, where any person with an Internet connection has seemingly all the information in the world at their fingertips. Yet, while the Internet has greatly expanded the ability to share knowledge, it has also made issues of privacy more complicated, with many worrying their own personal information, including their activity on the Internet, may be observed without their permission. Not only are government agencies able to track an individual’s online movements, but so too are corporations, who have only become bolder in using that information to target users with ads. Unseen eyes are everywhere. In this climate of data gathering and privacy concerns, a browser called Tor has become the subject of discussion and notoriety. Like many underground phenomena on the Internet, it is poorly understood, shrouded in the sort of technological mysticism that people often ascribe to things like hacking or bitcoins. RelatedYou can now read ProPublica on the Dark Web Tor is software that allows users to browse the Web anonymously. Developed by the Tor Project, a nonprofit organization that advocates for anonymity on the internet, Tor was originally called The Onion Router because it uses a technique called onion routing to conceal information about user activity. Perhaps ironically, the organization receives the bulk of its funding from the United States government, which views Tor as a tool for fostering democracy in authoritarian states. Why the Internet isn’t secure To understand how Tor is able to protect a user’s identity as they browse the Internet, it seems prudent to discuss exactly how the Internet works. The Internet is, at its most basic, the series of connections between computers across great distance. In the beginning, computers were isolated, unable to communicate with each other. As the tech got more advanced, engineers were able to physically link computers together, creating early networks. These networks still required the computers to be relatively near each other, however. Eventually, advances in fiber optics enabled networks to connect across continents, allowing for the Internet to be born. Some computers house the data stored on the Internet, including web pages like Google. These computers are known as “servers.” A device used to access this information, such as a smartphone or PC, is known as a client. The transmission lines that connect clients to servers come in a variety of forms, whether fiber optic cables or wireless signals, but they are all connections. Although clients initiate connections to get information from servers, the flow goes both ways. Data is exchanged across the Internet in packets. These packets contain information about the sender and the destination, and certain individuals and organizations can use this data to monitor who is doing certain things or accessing certain information on the Web. It is not just the server that can see this data. Traffic analysis is big business, and many organizations, both private and governmental, can monitor the messages flowing between clients and servers. How, then, does Tor keep the user’s information secret? How Tor has the answer There are two key aspects to onion routing. First, the Tor network is composed of volunteers who use their computers as “nodes.” As mentioned earlier, during normal browsing, information travels across the Internet in packets. When a Tor user visits a website, however, their packets do not simply travel to that server. Instead, Tor creates a path through randomly assigned nodes on that the packet will follow before reaching the server. nodesillustration2 The other important aspect of onion routing is how the packets are constructed. Normally, a packet will include the sender’s address and the destination, not unlike a letter. When using Tor, the packet is wrapped in successive layers of packets, like a nesting doll. Anatomy of an onion packet. Original message is in black When the user sends the packet, the top layer tells it to go to Router A, the first stop on the circuit. When it is there, Router A takes off the first layer. The next layer tells Router A to send the packet onward to Router B. Router A does not know the ultimate destination, only that the packet came from the user and went to B. Router B peels off the next layer, seeing that the next stop is Router C. The process continues until the message reaches its destination. At each stop, the node only knows the available information: the last place the packet was, and the next place it will be. No node knows the complete path, and neither would anyone who observes the message being sent from a node. How to get Tor In keeping with the ideological aims of the Tor Project, Tor is free to use. Simply download and install the browser, which is a modified version of Firefox available for Windows, Mac OS X, and Linux. For mobile browsing, there is also an Android app called Orbot. Note that while the Tor browser is already configured to work properly, users on networks with firewalls or other security systems may experience difficulties. Moreover, careless Internet usage can still compromise one’s anonymity. Tor’s website has a comprehensive list of things to avoid doing while using the browser, as well as fixes for any problems that arise. The Deep Web and Tor’s hidden services Tor is valuable as a tool to protect the user’s privacy, but that is not its only function. The other, more infamous use for Tor is as a gateway into the Deep Web, the massive portion of the Web that is not indexed by search engines. The term “Deep Web” is thrown around in popular discourse, often in tones reserved for bogeymen. There are good reasons for this, but most of the Deep Web is fairly mundane. It is merely all the information that cannot be easily accessed through a Web search, which is a lot of data, actually. The Internet, to use an old but apt cliche, is like the ocean. Like the surface of the world’s oceans, the surface of the Internet is mapped out, easily found via Google search. The bulk of the world’s oceans lie beneath the surface, however. The bulk of the Internet (around 80 percent) comprises pages unknown to most people, locked behind passwords and protocols. Silk Road Silk Road, one of the most famous (and sordid) sites on the Tor network   Tor allows web pages, like clients, to protect their anonymity, by configuring a server to connect with clients at a Tor relay in between. The server does not need to provide the IP address, and the user does not need it, instead using an “onion address,” a 16 character code that clients enter in place of a traditional URL. The hidden pages on the Tor network comprise one of the most famous darknets, networks only accessible through specific protocols. A phrase like darknet conjures up images of shady dealings, and not without cause; some of the most notable hidden sites are used for trafficking illegal goods, such as the Silk Road, a popular site for selling drugs which was shut down by the FBI in 2013. Who uses Tor, and why? Anonymity is Tor’s bread and butter, and as such it is probably impossible to ever get a comprehensive view of its userbase. There are certain trends that become apparent, however, and some Tor advocates are especially vocal about their reasons for using the service. Tor has become popular with journalists and activists in countries with restrictions on the Internet and expression. Countries like China are known for censoring their citizens’ access to the Web; Tor provides a way around this control. For whistleblowers, Tor provides a safe avenue to leak information to journalists. In fact, Edward Snowden released information on the NSA’s PRISM program to news organizations via Tor. One doesn’t need to be a freedom fighter to appreciate Tor, however. Many academics and ordinary citizens endorse Tor as a tool to keep privacy and freedom of expression alive in the Information Age. Despite the Tor Project’s good intentions, Tor has developed a bad reputation in the mainstream press, and not without cause. Just as large cities, with growth and prosperity, attract criminals, the growth of Tor and the cover it provides has made the network a refuge for unsavory individuals. To be fair, the fact that Tor allows such communities to grow is troubling. However, it is important to note that criminal activity on Tor is a consequence, not a goal, of the Project’s commitment to freedom of expression. By January 19, 2016 Full article: Source: What is Tor? A Beginner’s Guide to the Deep Web | Digital Trends Leave a Reply Please log in using one of these methods to post your comment: WordPress.com Logo You are commenting using your WordPress.com account. Log Out / Change ) Twitter picture You are commenting using your Twitter account. Log Out / Change ) Facebook photo You are commenting using your Facebook account. Log Out / Change ) Google+ photo You are commenting using your Google+ account. Log Out / Change ) Connecting to %s
__label__pos
0.620451
Take the tour × Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required. I am trying get a mandelbrot image clearly with the sequential programming in C++, but I am getting a segmentation fault during runtime. I have no idea about the seg. fault, but my program is perfectly compiling with no errors. #include <stdio.h> #include <stdlib.h> #include <time.h> int file_write(unsigned int width, unsigned int height) { unsigned int **color = NULL; FILE *fractal = fopen("mandelbrot_imageSequential.ppm","w+"); if(fractal != NULL) { fprintf(fractal,"P6\n"); fprintf(fractal,"# %s\n", "Mandelbrot_imageSequential.ppm"); fprintf(fractal,"%d %d\n", height, width); fprintf(fractal,"40\n"); int x = 0, y = 0; unsigned int R = 0, G = 0, B = 0; for(x = 0; x < width; ++x) { for(y = 0; y < height; ++y) { R = (color[y][x]*10); G = 255-((color[y][x]*10)); B = ((color[y][x]*10)-150); if(R == 10) R = 11; if(G == 10) G = 11; if(B == 10) B = 11; putc(R, fractal); putc(G, fractal); putc(B, fractal); } } fclose(fractal); } return 0; } int method(int x, int y, int height, int width, double min_re, double max_re, double min_im, double max_im, int max_iterations) { double threshold = 4; double x_factor = (max_re-min_re)/(width-1); double y_factor = (max_im-min_im)/(height-1); double c_im = max_im - y*y_factor; double c_re = min_re + x*x_factor; double Z_re = c_re, Z_im = c_im; unsigned int col = 0; for(unsigned n = 0; n < max_iterations; ++n) { double Z_re2 = Z_re*Z_re, Z_im2 = Z_im*Z_im; if(Z_re2 + Z_im2 > threshold) { col = n; break; } Z_im = 2 * Z_re * Z_im + c_im; Z_re = Z_re2 - Z_im2 + c_re; } return col; } int main(int argc, char *argv[]) { unsigned int width; unsigned int height; unsigned int max_iterations; unsigned int **color = NULL; int x,y; double threshold; double min_re; double max_re; double min_im; double max_im; unsigned int NUM_OF_THREADS; if(argc != 10) { printf("There is an error in the input given.\n"); return 0; } else { height = atoi(argv[1]); width = atoi(argv[2]); max_iterations = atoi(argv[3]); min_re = atof(argv[4]); max_re = atof(argv[5]); min_im = atof(argv[6]); max_im = atof(argv[7]); threshold = atoi(argv[8]); NUM_OF_THREADS = atoi(argv[9]); } color = (unsigned int**)malloc(height*sizeof(unsigned int*)); printf("height = %d\twidth = %d\tmaximum_iterations = %d\tminimum_x-value = %.2f\tmaximum_x-value = %.2f\tminimum_y-value = %.2f\tmaximum_y-value = %.2f\tthreshold_value = %.2f\tno. of threads = %d\t\n",height,width,max_iterations,min_re,max_re,min_im,max_im,threshold,NUM_OF_THREADS); for(x = 0; x < height; x++) { color[x] = (unsigned int*)malloc(width*sizeof(unsigned int)); } time_t ts,te; time(&ts); method(x,y,height,width,min_re,max_re,min_im,max_im,max_iterations); time(&te); double diff = difftime(te,ts); file_write(width, height); printf("Total Time elapsed: %f\n",diff); return 0; } how to correct this segmentation fault share|improve this question 1   Let your debugger find the segfault spot. –  Anthales Apr 25 '12 at 10:47   ok, i will try it. –  visanio_learner Apr 25 '12 at 10:49 3   I could spot one problem in your file_write: you never allocate memory for your unsigned int **color or rather, you didn't pass the color out of your main to the function. –  Anthales Apr 25 '12 at 10:50 1   This variable: unsigned int **color = NULL; is the where the segfault is happening. You don't initialize it and yet you dereference it in the code. –  trojanfoe Apr 25 '12 at 10:52 2   Seriously broken indentation. :| –  unwind Apr 25 '12 at 10:52 show 2 more comments 2 Answers At least one problem is in the file_write function. 1. unsigned int **color = NULL; 2. R = (color[y][x]*10); I assume the color should be an input parameter. share|improve this answer   can i know what is the solution for this seg fault? –  visanio_learner Apr 25 '12 at 11:03   Sure. 1. int file_write(unsigned int width, unsigned int height, unsigned int **color) {...}, 2. file_write(width, height, color);. But there is another problem. The color is allocated in the main, not initialized and not used anywhere, i.e. the function file_write saves something. –  megabyte1024 Apr 25 '12 at 11:08   now i try to run it on C compiler instead of running it C++, it is showing an error and note > error: 'for' loop initial declarations are only allowed in C99 mode > note: use option -std=c99 or -std=gnu99 to compile your code –  visanio_learner Apr 25 '12 at 11:09   i know that seg fault mainly occurs due to improper memory allocation, that is trying to access a variable which is not allocated... –  visanio_learner Apr 25 '12 at 11:11   change for(unsigned n = 0; n < max_iterations; ++n) to unsigned n; for(n = 0; n < max_iterations; ++n) –  megabyte1024 Apr 25 '12 at 11:16 show 8 more comments If you are on Linux machine do the following : $ulimit -c unlimited Then run the code. Notice a core.[pid] file is generated. fire up gdb like following $gdb ./your_app core.[pid] It will take you the statement where segfault occurred. issue a "backtrace" command in gdb prompt to see the call hierarchy. Remember compiling with "-g" flag to get more verbose gdb output. share|improve this answer   i tried to run gdb but it says there is no such file or directory... –  visanio_learner Apr 25 '12 at 13:34   what arguments you have provided to gdb? are you in the directory where your binary resides? have you verified the existence of "core" file? –  Aftnix Apr 25 '12 at 13:41   yeah i am in my directory... –  visanio_learner Apr 25 '12 at 13:55   and als there is a file with huge amount size core filename –  visanio_learner Apr 25 '12 at 13:56   then just type $gdb ./<your binary name> <your core file name> –  Aftnix Apr 25 '12 at 13:59 show 5 more comments Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.969746
Hey there Sign in to join this conversationNew here? Join for free C4 integration!! Announcements Posted on • Thread Starter • 0 followers Offline ReputationRep: Integrating using trig identities. I came across this example in my book... \int sin^2x dx which is replaced by \int \frac{1}{2}(1-cos2x) dx the result is then \frac{1}{2}(x-\frac{1}{2}sin2x) + C I don't understand why it is only the bit in the brackets from \int \frac{1}{2}(1-cos2x) dx that gets integrated? Is there a step inbetween where \frac{1}{2} is moved before the integral sign? e.g. \frac{1}{2} \int (1-cos2x) dx ? Any help is much appreciated!! • 16 followers Offline ReputationRep: (Original post by icouldsay) Integrating using trig identities. I came across this example in my book... \int sin^2x dx which is replaced by \int \frac{1}{2}(1-cos2x) dx the result is then \frac{1}{2}(x-\frac{1}{2}sin2x) + C I don't understand why it is only the bit in the brackets from \int \frac{1}{2}(1-cos2x) dx that gets integrated? Is there a step inbetween where \frac{1}{2} is moved before the integral sign? e.g. \frac{1}{2} \int (1-cos2x) dx ? Any help is much appreciated!! Yep - 1/2 is a constant so you can move it outside. • Thread Starter • 0 followers Offline ReputationRep: Thank you!! Reply Submit reply Register Thanks for posting! You just need to create an account in order to submit the post 1. this can't be left blank that username has been taken, please choose another Forgotten your password? this is what you'll be called on TSR 2. this can't be left blank this email is already registered. Forgotten your password? never shared and never spammed 3. this can't be left blank 6 characters or longer with both numbers and letters is safer 4. this can't be left empty your full birthday is required 1. By joining you agree to our Ts and Cs, privacy policy and site rules 2. Slide the button to the right to create your account Slide to join now Processing… Updated: May 28, 2012 New on TSR Student crowdfunds degree Graduate raises £26,000 online for Masters course Article updates Reputation gems: You get these gems as you gain rep from other members for making good contributions and giving helpful advice.
__label__pos
0.999524
Printing HTML Attritbutes with jquery in a loop 301 November 22, 2016, at 10:03 AM i try to loop trough Objects in a Database (parse.com) and would like to print these results with attributes from Bootstrap. I'm a beginner and don't understand why it's not possible how i did it. i know there is .attr() but i don't get it how i can use this in my example. This is my code: var Insider = Parse.Object.extend("Insider"); function getPosts() { var query = new Parse.Query(Insider); query.find({ success: function(results) { var output = ""; for (var i in results) { var name = results[i].get("name"); var catego = results[i].get("cate"); var imageurl = results[i].get("image"); var tpp = results[i].get("tipp"); output += "<ul class="media-list">"; output += "<li class="media">"; output += "<div class="media-left">"; output += "<a href="#">"; output += "<img id = "two" class="media-object" alt="...">" output += "<h4>+ + name + "</h4>"; output += "</a>" output += "</div>" } $("#list").html(output); }, error: function(error){ console.log("Query error:" + error.message); } }); } getPosts(); }); Any help much appreciated! Rent Charter Buses Company READ ALSO Need help parsing jquery datatables editor data Need help parsing jquery datatables editor data I have a data format that I receive from jquery data tables editor Datatables Editor which looks like the one below and I need to parse it so that I can store it into db but I have not figured out a way of doing so. . 385 Disable browser&#39;s autocomplete textboxes in asp.net c# Disable browser's autocomplete textboxes in asp.net c# How to disable browser's autocomplete effect on all textboxes in asp. net c# application. 421 Validate Input only on blur or loose focus Validate Input only on blur or loose focus I am using - victorjonsson/jQuery-Form-Validator. 363
__label__pos
0.947421
what : Home > Authors > W > Nathan Wolek : 30 objects/ 2 libraries page : 1 2 Objects cartodb~External Computes the amplitude in decibels of an fft bin. Useful for dynamics processing in the frequency domain, such as spectral gating. cartonormdb~External Computes the amplitude in decibels of an fft bin, normalized to value in first bin of each fft group. This form of db computation is typically used to analyze the spectral effects of a window. complex.*~External Computes the complex multiplication of two real/imaginary pairs. A good way to convolve two frequency domain signals. complex./~External Computes the complex division of two real/imaginary pairs. complex.1over~External Computes the inverse of a real/imaginary pair. cpPan~External constant power pan dbtocar~External Computes the real and imaginary values based on a db amplitude and phase value. Useful for dynamic processing in the frequency domain, such as spectral gating. grain.bang~External granular synthesis - Outputs a single grain when a bang is received. grain.phase~External granular synthesis - Outputs a stream of grains with the window controled by a phasor object. grain.pulse~External granular synthesis - Outputs a single grain when it detects a pulse from a 'train~' object. grain.stream~External granular synthesis - Outputs a stream of grains gran.ASstream.file~Abstraction single stream of asynchronous grains gran.ASstream.live~Abstraction single stream of asynchronous grains gran.chord.file~Abstraction grains at pitches within a "chord" gran.chord.live~Abstraction grains at pitches within a "chord" gran.cloud.file~Abstraction variable density of individual grains with random offset, pitch, gain and panning gran.cloud.live~Abstraction variable density of individual grains with random offset, pitch, gain and panning gran.groove.file~Abstraction like groove~ object, with independent pitch and playback speed (granular synthesis) gran.pitch.file~Abstraction produce sampled grains shifted to a new pitch gran.pitch.live~Abstraction produce sampled grains shifted to a new pitch gran.play.file~Abstraction granular synthesis, similar to the play~ object gran.space2.file~Abstraction 8 streams of grains, evenly panned and out-of-phase gran.space2.live~Abstraction 8 streams of grains, evenly panned and out-of-phase gran.space8.file~Abstraction Eight streams of grains are evenly out-of-phase and output individually. gran.space8.live~Abstraction Eight streams of grains are evenly out-of-phase and output individually. Libraries FFTexternals A small collection of externals used for various spectral processing. Includes objects for computing amplitude in decibels and a few complex math functions. Granular Toolkit set of externals and abstractions developed using several granular synthesis concepts. Effects available in this download include pitch shifting, spatializing, \"clouds\", chord production and looping. 4851 objects and 135 libraries within the database Last entries : January 1st, 2021 Last comments : 0 0 visitories and 4470958 members connected RSS Site under GNU Free Documentation License   
__label__pos
0.78774
Firefox, IE8, and opera work fine, but in safari, it makes the two DIVs in the middle of the page go into one DIV. I already tried to make a "master" DIV where i put both DIVs into it but it still doesn't work. Then I put float:left on the left one, and float:right on the right. but they just flew all over the page. I've posted my html and css. Someone please tell me what im doing wrong. thx in advance. UPDATE by o.k.w: Here are the screenshots of the problem on the 2 browsers: Screenshot on Safari/Chrome Safari Screenshot on Firefox Firefox 2 answers o.k.w 2355 0 points This was chosen as the best answer Ok, I just spent 30min of my christmas on this question. Haha. Anyway, the main issue is the CSS styles are too 'messy'. I can't really put it in words, you can compare the codes I did and see for yourself. It's not a Safari issue too, but webkit-based browser. Chrome too has problem rendering your codes. I've merged the CSS into an the HTML as an inline one. I'll post the screenshot in awhile. Here we go: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="description" content=" ZEROENCRYPTION.com is a web design service that creates sites for a price that will fit right into your budget!"/><meta name="keywords" content="html, web design, css, cheap web designers, affordable web designers, web site creator"/> <title>ZEROENCRYPTION Web Design</title> <style type="text/css"> body, html{ background-color: black; font-family: "times new roman", times, arial, serif; margin: 0; padding: 0; } #header{ background-color:#6D7B8D; width: 100%; height: 75px; } #heading{ font-size: 52px; color: #98AFC7; font-style: italic; letter-spacing: 20px; font-weight: 400; } #nav { background-color: #646D7E; width: 100%; height: 30px; text-align: center; } #nav a { /*format all nav links with margins*/ margin-left: 30px; margin-right: 30px; } a:link {color: #F88017; text-decoration: none; font-size: 23px;font-weight: 100;} a:active {color: #F88017; text-decoration: none; font-size: 23px;} a:visited {color: #F88017; text-decoration: none; font-size: 23px;} a:hover {color: #F88017; text-decoration: underline; font-size: 23px;} #master{ background-color: green ; width: 100%; margin-top: 10px; } #welcome{ font-size: 26px; color: #616D7E; font-style:italic; font-weight: 900; margin-top: 20px; } #paragraph{ font-size: 20px; color: black; margin-top: 80px; word-spacing: 1px; clear: both; padding: 80px 20px; } #right{ background-color: silver; width: 600px; height: 600px; overflow: hidden; float: right; } #left{ height: 400px; width: 350px; background-color: silver; overflow:hidden; float: left; } #around { height: 100%; margin: 0 auto; width: 970px; } #prev { padding: 30px; clear: both; } #prev div { /* format both 'previous boxes' */ height: 223px; width: 253px; background-color: white; border: 2px solid #2B547E; } #previous { float: left; } #previous2 { float: right; } /* all styles from this point down are not modified*/ #comingsoon{ font-style:italic; margin-top: -28px; margin-left: 240px; font-weight: 400; } #inside{ height: 80%; width: 80%; background-color: white; border:#2B547E 2px solid; } #inside2{ width: 100%; height: 34px; background-color: red; margin-top: 80px; } #leftcomingsoon { font-size: 30px; color: white; font-style: italic; margin-top: -10px; } #copyright{ font-size: 11px; color: white; margin-top: 3%; font-weight: 900; margin-left: 670px; } #updates{ font-size: 24px; color: #616D7E; font-style: italic; margin-top: 18px; } </style> </head> <body> <div id="around" align="center"> <div id="header"> <h1 id="heading">ZEROENCRYPTION</h1> </div> <div id="nav"> <a id="home" href="http://www.ZEROENCRYPTION.com">Home</a> <a id="contact" href="http://www.ZEROENCRYPTION.com">Contact</a> <a id="about" href="http://www.ZEROENCRYPTION.com">About</a> <a id="portfolio" href="http://www.ZEROENCRYPTION.com">Portfolio</a> <a id="blog" href="http://www.ZEROENCRYPTION">Blog</a> <a id="computer" href="http://www.computersquirrel.com">Computer Repairs</a> </div> <div id="master" align="center"> <div id="left"><p id="updates">UPDATES</p> <div id="inside"> <div id="inside2"><p id="leftcomingsoon">coming soon!</p> </div> </div> </div> <div id="right"><p id="welcome">Zeroencryption's Portfolio</p><p id="comingsoon">coming soon!</p> <div id="prev"> <div id="previous"></div> <div id="previous2"></div> </div> <p id="paragraph">Want a website? Starting a business? ready to take your already existing business to the web? No matter what the case is, you've found the right place. Here at Zeroencryption, we offer affordable web design to fit your budget. To learn more, visit our about page.</p> </div> </div> <div id="bottom"> </div> </div> </body> </html> Answered over 8 years ago by o.k.w • I just tried it on my laptop but i cant tell what it looks like as i dont have safari. but i think itll work. thank you so much and merry christmas. ive been trying this ffor a while and i couldnt understand how to fix it. so what did you do exactly? canyonchase1 over 8 years ago • @canyonchase1: You can check the screenshot I posted in the other answer. It is not an exact replical in terms of layout (i.e. margin/padding) but you can tweak it yourself. Good luck! o.k.w over 8 years ago o.k.w 2355 2 points Somehow I can't edit my post anymore, I suspect the HTML I posted conflicted with the scripts? :P Anyway here's the screenshot on Safari ousing my modified codes: New Codes Tested it on Chrome/FF/IE8 as well. Answered over 8 years ago by o.k.w
__label__pos
0.722171
JSON Web Tokens (JWTs) JSON Web Token is an open standard that defines a compact and self-contained way for securely transmitting digitally signed information between parties as a JSON object. Compact: it can be sent through an URL, POST parameter, or inside an HTTP header. Self-contained: the payload has all the necessary information about the user. Structure of JWT JWTs contain three parts separated by a dot(.) and they are: • Header • Payload • Signature So the JWT look like this: hhhhhhhh.pppppppp.sssssssssss Each part is Base64url encoded. Header The header usually has two parts: • The type of the token • The hashing algorithm used in signing the token The image below shows an example of a header alg: is the algorithm used for signing the token, and here it is the HMAC SHA256 typ: is the type of the token which is always JWT Payload The second part of the JWT. It contain claims, which are information about an entity and other data. Claims are three types: registered (predefined claims), public (User defined), and private(custom claims used to share information between parties). The image below present an example of a payload The information contained in the payload are protected against tampering and modification, but they can be read by anyone because they are encoded not encrypted. So you should not put any secret information in the payload unless you encrypt them. Signature The signature is the third part of the JWT. it can be created by taking the base64 encoded header, the base64 encoded payload, a secret, the algorithm specified in the header and sign that. Example: { HMACSHA256 (base64UrlEncode(header) + "." + base64UrlEncode(payload), secret) } The algorithm used in the previous example is the HMAC SHA256. An Asymmetric hashing algorithm with a public/private key pair can also be used like RSA. How JWT work The image below describes how the JWT is used in authentication. Implementation There are libraries for implementing JWT in many different programming language. Every programming language has multiple libraries, and they differ in the syntax. Java JWT example The code below show how JWT can be created and verified. The library used in this example is jjwt. The signing was done using RS256 algorithm. // import the necessary packages import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.security.Keys // specifying the algorithm and the public/private key pairs KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.RS256) // creating the signed JWT String jws = Jwts.builder() .setHeaderParam("typ", "JWT") .claim("Name", "Najy") .claim("admin", true) .signWith(keyPair.getPrivate()) .compact(); // Verifying the JWT try{ Jws jws1; jws1 = Jwts.parser() .setSigningKey(keyPair.getPublic()) .parseClaimsJws(jws); out.println("Signature verified, The JWT can be trusted"); out.println("Header: " + jws1.getHeader()); out.println("Payload: " + jws1.getBody()); } catch (Exception ex){ // in case JWT was altered   out.println("Error: " + ex.getMessage()); } References https://jwt.io/introduction/ https://auth0.com/learn/json-web-tokens/ https://en.wikipedia.org/wiki/JSON_Web_Token https://github.com/jwtk/jjwt
__label__pos
0.690256
Contents Implementing a custom Akka Streams graph stage This article was originally posted at Jacek's blog. Background Akka Streams offers a number of predefined building blocks for your graphs (i.e. processing pipelines). Should you need a non-standard solution, there's an API to help you write the custom part of the graph. In this post I'm going to walk you through implementing your own graph stage. Recap: Akka Streams concepts Since the stream processing terminology heavily depends on the library/toolkit you are using, here is a quick reminder of what things are called in the Akka Streams world: the producer is called a Source, the consumer - a Sink and the processing stages are Flows. Each of those is a specialized graph stage whose type is determined by the number of inputs and outputs - a Source has no inputs and a single output, a Sink has a single input and no outputs, a Flow has a single input and a single output. In terms of the types, each part of the graph is a GraphStage with a given Shape - with the most basic shapes being: SourceShape, FlowShape and SinkShape. There are also other more complex Shapes available, used for modelling such concepts as broadcasting or merging elements of the stream, but those are out of the scope of this post. The use case Let's say that having a stream of elements of type E you want to observe their arbitrary property of type P, accumulate the elements as long as the property remains unchanged and only emit an immutable.Seq[E] of accumulated elements when the property changes. In a real-life example the elements can be e.g. lines in a CSV file which you would like to group by a given field. Anatomy of a custom graph stage A custom graph stage is nothing more than an implementation of: abstract class GraphStage[S <: Shape] In our example the stage is going to have a single input and a single output, which makes it a Flow whose shape is: FlowShape[E, immutable.Seq[E]] The definition of the stage thus becomes: final class AccumulateWhileUnchanged[E] extends GraphStage[FlowShape[E, immutable.Seq[E]]] { // ... } Now you just need to implement two methods • def shape: FlowShape - to provide a concrete shape • def createLogic(attributes: Attributes): GraphStageLogic - to provide your custom logic of the stage Let's now dig into the details of those two methods. Implementing a custom graph stage Providing a custom FlowShape A FlowShape simply consists of an Inlet and an Outlet, i.e. the ports of the stage. To define a port, you need to provide its name and data type. After defining the ports, the stage implementation becomes: final class AccumulateWhileUnchanged[E] extends GraphStage[FlowShape[E, immutable.Seq[E]]] { val in = Inlet[E]("AccumulateWhileUnchanged.in") val out = Outlet[immutable.Seq[E]]("AccumulateWhileUnchanged.out") override def shape = FlowShape(in, out) } Providing a custom GraphStageLogic Since the GraphStages are meant to be reusable, it is crucial to keep them immutable, i.e. not to put any mutable state inside them. On the other hand, however, the stage we are implementing here is definitely stateful - its state consists of the accumulated elements. Here is where the GraphStageLogic comes to the rescue - since a new instance of it is created for every materialization of the flow, it is the one and only place to keep the mutable state in. Within the GraphStageLogic, apart from keeping the mutable state, you may also define handlers for the onPush() and onPull() events. The onPush() event occurs when a new element from the upstream is available and can be acquired using grab(). The onPull(), on the other hand, occurs when the downstream is ready to accept a new element which can be sent with push(). So here is what a draft implementation of the GraphStageLogic with the handlers is going to look like: override def createLogic(attributes: Attributes) = new GraphStageLogic(shape) { setHandlers(in, out, new InHandler with OutHandler { override def onPush(): Unit = { // ... } override def onPull(): Unit = { // ... } }) } To implement the actual accumulating logic, you need to: • know how to extract the observed property of the incoming elements, • keep track of the incoming elements in some kind of a buffer. Extracting the observed property The easiest way to know which property to observe is to have the user provide a function which extracts this property - so you need to adjust the stage definition a bit: final class AccumulateWhileUnchanged[E, P](propertyExtractor: E => P) extends GraphStage[FlowShape[E, immutable.Seq[E]]] { Keeping track of the incoming elements The internal state of your stage logic will consist of: • an Option[P] to keep the current value of the observed property (empty until the first element arrives), • a Vector[E] to accumulate the elements (cleared when the observed property changes). When the next input element arrives (in onPush()), you want to extract its property and check if it differs from the current value. If there is no current value yet or the values are equal, you add the element to the buffer and pull() the input, otherwise you push() the buffer contents downstream and clear the buffer. When the downstream requests a new sequence of elements with onPull(), you just need to pull() the input in order to indicate, that the stage is ready to accept a new incoming element. An additional case that you need to handle is when the upstream has completed (i.e. no more input elements are going to arrive or there was an error in the upstream) - then you need to push the last elements from the buffer (unless it is empty) and complete the stage afterwards. Moreover, to be nice to memory and the GC, you may wish to clear the buffer after the stage is complete. The full implementation of the above concepts is going to be something like: final class AccumulateWhileUnchanged[E, P](propertyExtractor: E => P) extends GraphStage[FlowShape[E, immutable.Seq[E]]] { val in = Inlet[E]("AccumulateWhileUnchanged.in") val out = Outlet[immutable.Seq[E]]("AccumulateWhileUnchanged.out") override def shape = FlowShape.of(in, out) override def createLogic(attributes: Attributes) = new GraphStageLogic(shape) { private var currentState: Option[P] = None private val buffer = Vector.newBuilder[E] setHandlers(in, out, new InHandler with OutHandler { override def onPush(): Unit = { val nextElement = grab(in) val nextState = propertyExtractor(nextElement) if (currentState.isEmpty || currentState.contains(nextState)) { buffer += nextElement pull(in) } else { val result = buffer.result() buffer.clear() buffer += nextElement push(out, result) } currentState = Some(nextState) } override def onPull(): Unit = { pull(in) } override def onUpstreamFinish(): Unit = { val result = buffer.result() if (result.nonEmpty) { emit(out, result) } completeStage() } }) override def postStop(): Unit = { buffer.clear() } } } If you are wondering why emit() is used instead of push() in onUsptreamFinish() (line 40), the answer is - because it is not possible to push a port which has not been pulled. Once the upstream is finished, the buffer may still contain the final group of accumulated elements - but chances are that the output port has not been pulled after the previous group was pushed. You want, however, to send the final group anyway - that is where emit() comes to the rescue - when it detects that the output port is not available (i.e. cannot be pushed), it replaces the OutHandler with a temporary one and only then does it execute the actual push(). Now you are ready to use the custom stage in your application with .via(new AccumulateWhileUnchanged(...)). For example, having a simple domain like: case class Element(id: Int, value: Int) object SampleElements { val E11 = Element(1, 1) val E21 = Element(2, 1) val E31 = Element(3, 1) val E42 = Element(4, 2) val E52 = Element(5, 2) val E63 = Element(6, 3) val Ones = immutable.Seq(E11, E21, E31) val Twos = immutable.Seq(E42, E52) val Threes = immutable.Seq(E63) val All = Ones ++ Twos ++ Threes } when you run: Source(SampleElements.All) .via(new AccumulateWhileUnchanged(_.value)) .runWith(Sink.foreach(println)) the output will be: Vector(Element(1,1), Element(2,1), Element(3,1)) Vector(Element(4,2), Element(5,2)) Vector(Element(6,3)) Testing There is a number of useful utilities to help you test your custom graph stages. With the help of those and using the SampleElements helper defined above, a sample test case for the above stage looks like: "AccumulateWhileUnchanged" should { "emit accumulated elements when the given property changes" in { val (_, sink) = Source(SampleElements.All) .via(AccumulateWhileUnchanged(_.value)) .toMat(TestSink.probe)(Keep.both) .run() sink.request(42) sink.expectNext(SampleElements.Ones, SampleElements.Twos, SampleElements.Threes) sink.expectComplete() } } The TestSink.probe (line 6) creates an instance of akka.stream.testkit.TestSubscriber.Probe, which offers methods such as expectNext() or expectComplete() (lines 10-11) to verify whether the stage behaves correctly. Summary After diligently going through this post, you should understand how the GraphStage API is designed and how to use it to implement your own graph stage. For even more details, please refer to the Custom stream processing section of the Akka Streams documentation. If you find the AccumulateWhileUnchanged stage useful, there is no need to rewrite it from scratch, since it is a part of akka-stream-contrib - a project which groups various add-ons to Akka Streams core. Blog Comments powered by Disqus.
__label__pos
0.97995
Back to home page Project CMSSW displayed by LXR          File indexing completed on 2024-04-06 12:05:01 0001 #ifndef DataFormats_Provenance_ElementID_h 0002 #define DataFormats_Provenance_ElementID_h 0003 0004 #include "DataFormats/Provenance/interface/ProductID.h" 0005 0006 #include <iosfwd> 0007 0008 namespace edm { 0009 /** 0010 * ElementID is a unique identifier for an element within a 0011 * container. It extends the ProductID concept by adding an index to 0012 * an object within a container. 0013 * 0014 * It provides both index() and key() methods so that it can be used 0015 * in place of Ref/Ptr in the interfaces of e.g. ValueMap or Association. 0016 */ 0017 class ElementID { 0018 public: 0019 using key_type = unsigned int; 0020 0021 ElementID() = default; 0022 explicit ElementID(edm::ProductID id, key_type ind) : index_(ind), id_(id) {} 0023 0024 bool isValid() const { return id_.isValid(); } 0025 ProductID id() const { return id_; } 0026 key_type index() const { return index_; } 0027 key_type key() const { return index_; } 0028 void reset() { 0029 index_ = 0; 0030 id_.reset(); 0031 } 0032 0033 void swap(ElementID& other); 0034 0035 private: 0036 key_type index_ = 0; 0037 ProductID id_; 0038 }; 0039 0040 inline void swap(ElementID& a, ElementID& b) { a.swap(b); } 0041 0042 inline bool operator==(ElementID const& lh, ElementID const& rh) { 0043 return lh.index() == rh.index() && lh.id() == rh.id(); 0044 } 0045 0046 inline bool operator!=(ElementID const& lh, ElementID const& rh) { return !(lh == rh); } 0047 0048 bool operator<(ElementID const& lh, ElementID const& rh); 0049 0050 std::ostream& operator<<(std::ostream& os, ElementID const& id); 0051 } // namespace edm 0052 0053 #endif
__label__pos
0.767588
blob: 9b5c27021c4129cf8e98405eca1627313f4aef90 [file] [log] [blame] /* * Copyright (c) 2006-2009 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black */ #include "cpu/nativetrace.hh" #include "base/socket.hh" #include "cpu/static_inst.hh" #include "debug/GDBMisc.hh" #include "params/NativeTrace.hh" using namespace std; namespace Trace { NativeTrace::NativeTrace(const Params *p) : ExeTracer(p) { if (ListenSocket::allDisabled()) fatal("All listeners are disabled!"); int port = 8000; while (!native_listener.listen(port, true)) { DPRINTF(GDBMisc, "Can't bind port %d\n", port); port++; } ccprintf(cerr, "Listening for native process on port %d\n", port); fd = native_listener.accept(); } void Trace::NativeTraceRecord::dump() { //Don't print what happens for each micro-op, just print out //once at the last op, and for regular instructions. if (!staticInst->isMicroop() || staticInst->isLastMicroop()) parent->check(this); } } // namespace Trace
__label__pos
0.948272
Ir para o conteúdo principal The Pixel 3a XL is the larger version of Google's third generation budget phones, and includes the same camera as Google's flagships. Available in Clearly White, Just Black, or Purple-ish. Released May 2019. 15 Perguntas Visualizar todos When I turn my screen off and back on screen becomes unresponsive. I recently replaced my screen and when I first turn it on everything works fine, but when I turn off the screen and then turn it back on, everywhere I touch just brings up the pull down menu. Responder a esta pergunta Também tenho esse problema Esta pergunta é pertinente? Pontuação 3 1 dos comentários TO the original poster, I am facing the exact same issue after replacing my broken screen, were you able to find a fix for your issue? por Adicionar um comentário 3 respostas Pergunta Mais Útil To anyone facing this issue, the problem seems to lie in the replacement screens themselves. A workaround is to go into Settings > System > Gestures and turn OFF “Double Tap To Check Phone" After turning this gesture off, the phone works normally. Esta resposta foi útil? Pontuação 1 Adicionar um comentário This sounds like a faulty display assembly or possibly even just a poorly seated cable. If you can, try to pop off the display connector and give both sides a gentle clean with some high % isopropyl alcohol. If the screen is still unresponsive, it’s likely to be a bad display assembly. And unfortunately if the same behavior is present on multiple displays, it’s possible the board was damaged somehow during repair, in which case, you may want to look for a new device or send it to a board repair service. Esta resposta foi útil? Pontuação 0 Adicionar um comentário TO the original poster, I am facing the exact same issue after replacing my broken screen, were you able to find a fix for your issue? Esta resposta foi útil? Pontuação 0 Adicionar um comentário Adicionar a sua resposta Sany Dan Muk será eternamente grato(a). Exibir estatísticas: Últimas 24 horas: 0 Últimos 7 dias: 2 Últimos 30 dias: 7 Duração total: 296
__label__pos
0.919356
1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors Dismiss Notice Dismiss Notice Join Physics Forums Today! The friendliest, high quality science and math community on the planet! Everyone who loves science is here! Calculus Morris Kline Inclination Of A Line 1. Sep 17, 2014 #1 1. The problem statement, all variables and given/known data On pages 65-66 of Calculus An Intuitive And Physical Approach, Mr. Kline discusses Inclinations of lines. In illustration 3A-7 he uses the substitution method to create a proof. But there is one step that I think he leaves out. He shows the equation tan A = tan(180 - B) = -tan(B). I understand that angle A = (180 - B) So I understand the first part of the equation. But what I want to know is what he does to the number 180 in the second part of the equation. 2. Relevant equations tan(A) = tan(180 - B) = -tan(B) 3. The attempt at a solution After researching Ptolomey's table of Chords and Rene Descartes, I know that negative numbers were not used in early mathematics. I also know that Euclid himself never considered negative numbers. I've heard that Fermat and Issac Newton were some of the first people to use negative numbers. But this still doesn't completely explain what happens to the number 180 in the second part of the equation.   Last edited by a moderator: Sep 17, 2014 2. jcsd 3. Sep 17, 2014 #2 Mark44 Staff: Mentor I don't have that textbook, so I assume that Kline also assumes that A and B are supplementary angles; i.e., that they add to 180°. It's really 180°, the number of degrees for an angle whose two rays form a straight line. Using the definition of the tangent as the rise/run for an acute angle of a right triangle, it's easy to see that the reference triangle for angle A and the reference triangle for angle B are congruent. This means that the rises of the two triangles are equal, and the bases are of the same length but pointing in the opposite directions. Therefore, tan(A) = -tan(B). There's really nothing mysterious about the disappearance of the 180° term.   4. Sep 17, 2014 #3 The textbook says as follows: An alternative method of describing the slope of a line with respect to the horizontal or x-axis utilizes the angle which the line makes with the axis. This angle of inclination is the counterclockwise angle whose initial side is the x-axis taken in the positive direction and whose terminal side lies on the line itself taken in the upward direction. Then is shows an illustration. A few sentences later it says, "The slope of a line and the angle of inclination both give the direction of the line. The slope of a line is m = y2 -y1 / x2 - x1. I've used the substitution method of mathematics for many years and I've done a comprehensive study of both Euclid and Descartes. I even studied Ptolomey's table of Chords. But none of these texts mention a reference angle. To this day I have no idea who invented the reference angle or why they invented such a mathematical term. I've asked many people and they are just as dumbfounded as I am. Now in a regular mathematical equation, when you use the substitution method, you have to make sure both sides of the equation are equal. So when someone presents an example equation like this: 68 = 180 - 112, you could substitute the number 68 for 180 - 112. But in this equation I couldn't just remove the number 180. Otherwise the equation would look like this: 68 = -112. And as we all know 68 does not equal -112. Now can you see my confusion?   5. Sep 17, 2014 #4 Ray Vickson User Avatar Science Advisor Homework Helper I am absolutely sure the book does not say [tex] m = y_2 - \frac{y_1}{x_2} - x_1 [/tex] as you wrote. Use parentheses!   6. Sep 17, 2014 #5 I apologize for my mistake. Let's try that again. It actually says m = (y2 - y1)/(x2 - x1). Now will you answer my question?   7. Sep 17, 2014 #6 Ray Vickson User Avatar Science Advisor Homework Helper I'm not sure I really understand what your question is. Could it be that you are confusing slope and angle? Slope = tan(angle) and angle = arctan(slope).   8. Sep 17, 2014 #7 As I've stated previously, I've used the substitution method for many years. So when I say 68 = 180 - 112, I can also say 68 = 68 because I can substitute the number 68 in the place of the mathematical statement 180 - 112. So when Morris Kline says tan(A) = tan(180 - B), I can agree with that. After all, in his illustration, A = 180 - B. But I get stuck when he says tan(A) = tan(180 - B) = -tan(B). The reason I get stuck is the same reason I would get stuck saying 68 = 180 - 112 = -112. After all, I know that 68 will never equal -112. What I'm asking is what happens to the number 180.   9. Sep 17, 2014 #8 Mark44 Staff: Mentor When you write this as text on a single line, you need parentheses, like so: m = (y2 -y1) / (x2 - x1) What you wrote would be interpreted as m = y2 - ##\frac{y1}{x2}## - x1 I'm not sure how useful it is to study "just" geometry, as presented in Euclid and Ptolemy. The combining of the geometry of the Greeks and the algebra of the Arabs and Indians) in analytic geometry was a large step forward in the understanding of mathematics of the time. With that in mind, it's helpful to think in terms of the unit circle for the trig functions. For a given angle in its standard position, one ray is along the positive x-axis from (0, 0) to (1, 0), and the other ray extends to a point (x, y) on the unit circle. If the angle is acute (lies in Quadrant I), the reference angle is the same as the angle. For an angle such as 135°, for which the terminal ray is in Quadrant II, the terminal ray hits the unit circle at (-√2/2, √2/2). For this angle, the reference angle is the one made by the terminal ray and the negative x-axis, and has a measure of 45°. All of the trig functions of 135° are the same in absolute value as for 45°, but fairly obviously, some of them are negative in value. For example, sin(135°) and sin(45°) are equal in value, but the cosines (and tangents) of the two angles are opposite in sign. It's not really a substitution "method." When you substitute one expression for another, you are merely replacing something by something else that has the same value. Yes. Kline is saying two things when A = 180° - B: 1. tan(A) = tan(180° - B). This part is clear to you, I believe. A and 180° - B are equal expressions, so they both have the same tangent value. 2. tan(A) = -tan(B). This is the part you're having trouble with. As I said in my first post, where this comes from is clear if you have the reference angles to draw on (which Euclid and Ptolemy didn't have). Let's fall back to my example, with A = 45° and B its supplement (= 135°). Notice that these angles add to 180°, a so-called straight angle. Angle A Reference point on unit circle: ( √2/2, √2/2) Angle B Reference point on unit circle: ( -√2/2, √2/2) On the unit circle, the x-coordinate gives the cosine of the angle, and the y-coordinate gives the sine of the angle. The ratio of the y-coordinate over the x-coordinate gives the tangent of the angle, so for this example, tan(A) = 1, and tan(B) = -1 = - tan(A). It's easy enough to show using ordinary geometry, that this equation holds for arbitrary angles A and B that are supplementary.   10. Sep 18, 2014 #9 I agree that the reference angle is the part that Mr. Kline left out. It isn't mentioned in Euclid, Ptolemy, or even Descartes work. As a matter of fact, no one I've spoken to so far has any idea as to the origin of reference angle. I'm sure no one just went to bed one night, woke up, and said I think reference angles are a great idea. Why Mr. Kline never mentioned the origin of reference angles is beyond me. It's even more amazing to me that so many people know nothing about the origin of reference angles. So where do they come from? And how do you substitute reference angles for equations like 180 - B?   11. Sep 18, 2014 #10 I will also mention that no one that I've spoken to so far knows when negative numbers were introduced into the Cartesian Coordinate system. Was it Fermat? Was it Issac Newton? Maybe someone here knows the answer.   12. Sep 18, 2014 #11 Ray Vickson User Avatar Science Advisor Homework Helper Google 'negative number'. According to the Wikipedia entry, "Negative numbers appeared for the first time in history in the Nine Chapters on the Mathematical Art, which in its present form dates from the period of the Chinese Han Dynasty (202 BC – AD 220)". Later, in the section entitled History it says "European mathematicians, for the most part, resisted the concept of negative numbers until the 17th century, although Fibonacci allowed negative solutions in financial problems where they could be interpreted as debits (chapter 13 of Liber Abaci, AD 1202) and later as losses (in Flos)." The article has more to say on the matter, but that should be enough to get you started. Google is your friend.   Last edited: Sep 18, 2014 13. Sep 18, 2014 #12 Mark44 Staff: Mentor Since this is a problem from a calculus text, the author probably assumed some knowledge of trigonometry on the part of the reader. I wouldn't expect any discussion of the unit circle or reference angles in works by the ancient Greeks, but Descartes might have used these concepts in his work of developing analytic geometry. As you might know, the Cartesian coordinate system is named after him. Nor do I, but I have never lost any sleep over it. Why? It would be impossible for the writer of a calculus text to include the origin of every term used in the book. Again, why is this so amazing? For most people it's enough to know about them and how to use them, and of little or no importance to know when they came about or who thought of them. 180 - B is not an equation - it's an expression. More precisely, it is 180° - B. In posts 2 and 8 I explained to the best of my ability how I believe Kline arrives at tan(A) = -tan(B) where A + B = 180°. Please reread those posts and see if they answer your question about his proof.   Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook Have something to add? Draft saved Draft deleted Similar Discussions: Calculus Morris Kline Inclination Of A Line 1. Vector calculus (Replies: 3) 2. Vector calculus (Replies: 7) 3. Calculus Intro (Replies: 3) Loading...
__label__pos
0.959012
HOW TO SHOP 1 Login or create new account. 2 Review your order. 3 Payment & FREE shipment If you still have problems, please let us know, by sending an email to [email protected] . Thank you! SHOWROOM HOURS Mon-Fri 9:00AM - 6:00AM Sat - 9:00AM-5:00PM Sundays by appointment only! Kallyas Template An Introduction To WebBluetooth quick summary With Progressive Web Apps, you can now use the web to build full-blown apps. Thanks to an enormous amount of new specifications and features, we can do things with the web that you used to need to write native apps for. However, talking to hardware devices was still a bridge too far up till now. Thanks to WebBluetooth, we can now build PWAs that can control your lights, drive a car or even control a drone. With Progressive Web Apps, the web has been ever more closely moving towards native apps. However, with the added benefits that are inherent to the web such as privacy and cross-platform compatibility. The web has traditionally been fantastic about talking to servers on the network, and to servers on the Internet specifically. Now that the web is moving towards applications, we also need the same capabilities that native apps have. The amount of new specifications and features that have been implemented in the last few years in browsers is staggering. We’ve got specifications for dealing with 3D such as WebGL and the upcoming WebGPU. We can stream and generate audio, watch videos and use the webcam as an input device. We can also run code at almost native speeds using WebAssembly. Moreover, despite initially being a network-only medium, the web has moved towards offline support with service workers. That is great and all, but one area has been almost the exclusive domain for native apps: communicating with devices. That is a problem we’ve been trying to solve for a long time, and it is something that everybody has probably encountered at one point. The web is excellent for talking to servers, but not for talking to devices. Think about, for example, trying to set up a router in your network. Chances are you had to enter an IP address and use a web interface over a plain HTTP connection without any security whatsoever. That is just a poor experience and bad security. On top of that, how do you know what the right IP address is? HTTP is also the first problem we run into when we try to create a Progressive Web App that tries to talk to a device. PWAs are HTTPS only, and local devices are always just HTTP. You need a certificate for HTTPS, and in order to get a certificate, you need a publicly available server with a domain name (I’m talking about devices on our local network that is out of reach). So for many devices, you need native apps to set the devices up and use them because native apps are not bound to the limitations of the web platform and can offer a pleasant experience for its users. However, I do not want to download a 500 MB app to do that. Maybe the device you have is already a few years old, and the app was never updated to run on your new phone. Perhaps you want to use a desktop or laptop computer, and the manufacturer only built a mobile app. Also not an ideal experience. WebBluetooth is a new specification that has been implemented in Chrome and Samsung Internet that allows us to communicate directly to Bluetooth Low Energy devices from the browser. Progressive Web Apps in combination with WebBluetooth offer the security and convenience of a web application with the power to directly talk to devices. Bluetooth has a pretty bad name due to limited range, bad audio quality, and pairing problems. But, pretty much all those problems are a thing of the past. Bluetooth Low Energy is a modern specification that has little to do with the old Bluetooth specifications, apart from using the same frequency spectrum. More than 10 million devices ship with Bluetooth support every single day. That includes computers and phones, but also a variety of devices like heart rate and glucose monitors, IoT devices like light bulbs and toys like remote controllable cars and drones. The Boring Theoretical Part Since Bluetooth itself is not a web technology, it uses some vocabulary that may seem unfamiliar to us. So let’s go over how Bluetooth works and some of the terminology. Every Bluetooth device is either a ‘Central device’ or a ‘Peripheral’. Only central devices can initiate communication and can only talk to peripherals. An example of a central device would be a computer or a mobile phone. A peripheral cannot initiate communication and can only talk to a central device. Furthermore, a peripheral can only talk to one central device at the same time. A peripheral cannot talk to another peripheral. A central device can talk to multiple peripherals at the same time and could relay messages if it wanted to. So a heart rate monitor could not talk to your lightbulbs, however, you could write a program that runs on a central device that receives your heart rate and turns the lights red if the heart rate gets above a certain threshold. When we talk about WebBluetooth, we are talking about a specific part of the Bluetooth specification called Generic Attribute Profile, which has the very obvious abbreviation GATT. (Apparently, GAP was already taken.) In the context of GATT, we are no longer talking about central devices and peripherals, but clients and servers. Your light bulbs are servers. That may seem counter-intuitive, but it actually makes sense if you think about it. The light bulb offers a service, i.e. light. Just like when the browser connects to a server on the Internet, your phone or computer is a client that connects to the GATT server in the light bulb. Each server offers one or more services. Some of those services are officially part of the standard, but you can also define your own. In the case of the heart rate monitor, there is an official service defined in the specification. In case of the light bulb, there is not, and pretty much every manufacturer tries to re-invent the wheel. Every service has one or more characteristics. Each characteristic has a value that can be read or written. For now, it would be best to think of it as an array of objects, with each object having properties that have values. Unlike properties of objects, the services and characteristics are not identified by a string. Each service and characteristic has a unique UUID which can be 16 or 128 bits long. Officially, the 16 bit UUID is reserved for official standards, but pretty much nobody follows that rule. Finally, every value is an array of bytes. There are no fancy data types in Bluetooth. A Closer Look At A Bluetooth Light Bulb So let’s look at an actual Bluetooth device: a Mipow Playbulb Sphere. You can use an app like BLE Scanner, or nRF Connect to connect to the device and see all the services and characteristics. In this case, I am using the BLE Scanner app for iOS. The first thing you see when you connect to the light bulb is a list of services. There are some standardized ones like the device information service and the battery service. But there are also some custom services. I am particularly interested in the service with the 16 bit UUID of 0xff0f. If you open this service, you can see a long list of characteristics. I have no idea what most of these characteristics do, as they are only identified by a UUID and because they are unfortunately a part of a custom service; they are not standardized, and the manufacturer did not provide any documentation. The first characteristic with the UUID of 0xfffc seems particularly interesting. It has a value of four bytes. If we change the value of these bytes from 0x00000000 to 0x00ff0000, the light bulb turns red. Changing it to 0x0000ff00 turns the light bulb green, and 0x000000ff blue. These are RGB colors and correspond exactly to the hex colors we use in HTML and CSS. What does that first byte do? Well, if we change the value to 0xff000000, the lightbulb turns white. The lightbulb contains four different LEDs, and by changing the value of each of the four bytes, we can create every single color we want. The WebBluetooth API It is fantastic that we can use a native app to change the color of a light bulb, but how do we do this from the browser? It turns out that with the knowledge about Bluetooth and GATT we just learned, this is relatively simple thanks to the WebBluetooth API. It only takes a couple of lines of JavaScript to change the color of a light bulb. Let’s go over the WebBluetooth API. Connecting To A Device The first thing we need to do is to connect from the browser to the device. We call the function navigator.bluetooth.requestDevice() and provide the function with a configuration object. That object contains information about which device we want to use and which services should be available to our API. In the following example, we are filtering on the name of the device, as we only want to see devices that contain the prefix PLAYBULB in the name. We are also specifying 0xff0f as a service we want to use. Since the requestDevice() function returns a promise, we can await the result. let device = await navigator.bluetooth.requestDevice({ filters: [ { namePrefix: 'PLAYBULB' } ], optionalServices: [ 0xff0f ] }); When we call this function, a window pops up with the list of devices that conform to the filters we’ve specified. Now we have to select the device we want to connect to manually. That is an essential step for security and privacy and gives control to the user. The user decides whether the web app is allowed to connect, and of course, to which device it is allowed to connect. The web app cannot get a list of devices or connect without the user manually selecting a device. After we get access to the device, we can connect to the GATT server by calling the connect() function on the gatt property of the device and await the result. let server = await device.gatt.connect(); Once we have the server, we can call getPrimaryService() on the server with the UUID of the service we want to use as a parameter and await the result. let service = await server.getPrimaryService(0xff0f); Then call getCharacteristic() on the service with the UUID of the characteristic as a parameter and again await the result. We now have our characteristics which we can use to write and read data: let characteristic = await service.getCharacteristic(0xfffc); Writing Data To write data, we can call the function writeValue() on the characteristic with the value we want to write as an ArrayBuffer, which is a storage method for binary data. The reason we cannot use a regular array is that regular arrays can contain data of various types and can even have empty holes. Since we cannot create or modify an ArrayBuffer directly, we are using a ‘typed array’ instead. Every element of a typed array is always the same type, and it does not have any holes. In our case, we are going to use a Uint8Array, which is unsigned so it cannot contain any negative numbers; an integer, so it cannot contain fractions; and it is 8 bits and can contain only values from 0 to 255. In other words: an array of bytes. characteristic.writeValue( new Uint8Array([ 0, r, g, b ]) ); We already know how this particular light bulb works. We have to provide four bytes, one for each LED. Each byte has a value between 0 and 255, and in this case, we only want to use the red, green and blue LEDs, so we leave the white LED off, by using the value 0. Reading Data To read the current color of the light bulb, we can use the readValue() function and await the result. let value = await characteristic.readValue(); let r = value.getUint8(1); let g = value.getUint8(2); let b = value.getUint8(3); The value we get back is a DataView of an ArrayBuffer, and it offers a way to get the data out of the ArrayBuffer. In our case, we can use the getUint8() function with an index as a parameter to pull out the individual bytes from the array. Getting Notified Of Changes Finally, there is also a way to get notified when the value of a device changes. That isn’t really useful for a lightbulb, but for our heart rate monitor we have constantly changing values, and we don’t want to poll the current value manually every single second. characteristic.addEventListener( 'characteristicvaluechanged', e => { let r = e.target.value.getUint8(1); let g = e.target.value.getUint8(2); let b = e.target.value.getUint8(3); } ); characteristic.startNotifications() To get a callback whenever a value changes, we have to call the addEventListener() function on the characteristic with the parameter characteristicvaluechanged and a callback function. Whenever the value changes, the callback function will be called with an event object as a parameter, and we can get the data from the value property of the target of the event. And, finally extract the individual bytes again from the DataView of the ArrayBuffer. Because the bandwidth on the Bluetooth network is limited, we have to manually start this notification mechanism by calling startNotifications() on the characteristic. Otherwise, the network is going to be flooded by unnecessary data. Furthermore, because these devices typically use a battery, every single byte that we do not have to send will definitively improve the battery life of the device because the internal radio does not need to be turned on as often. Conclusion We’ve now gone over 90% of the WebBluetooth API. With just a few function calls and sending 4 bytes, you can create a web app that controls the colors of your light bulbs. If you add a few more lines, you can even control a toy car or fly a drone. With more and more Bluetooth devices making their way on to the market, the possibilities are endless. CREATE ACCOUNT FORGOT YOUR DETAILS? TOP
__label__pos
0.535861
January 14, 2017 correlation Correlation Plot Let’s start visualizing correlation values in a plot.Open your RStudio and begin typing in !!! Let's import the library corrplot for correlation matrix visualization library(corrplot) Let's store the dataset mtcars into dataframe named DataFrame DataFrame <- mtcars Let's find the correlation matrix of this data set corrMatrix <- cor(DataFrame) Let'c visualize the correlation matrix.This plot will tell about the correlation between the feature variables in the data set. Dark red means correlation=-1 Dark blue means correlation=1 White means correlation=0 corrplot(corrMatrix, method="circle") correlation Correlation plot If you want to see the exact correlation value in the plot .Then run the following code corrplot(corrMatrix, method="number") correlation values Correlation values
__label__pos
0.987333
Skip navigation New Planet New Planet Author: İsmail DÖNMEZ, Gultekin Cakmakci Område:  Datavetenskap, STEM Labels: , STEM, Tips och tricks Main aim of this activity is letting participants to solve pre-determined tasks on a maze, using their coding, engineering and mathematical skills during the process. The aim of this activity is letting participants to solve pre-determined tasks on a maze, using their coding, engineering and mathematical skills during the process. There are four different starting points on the previously designed maze. Participants will be divided into groups. Then, each group will select a specific point on the mat and reach the end point. There are four different station points between the start and end points. Teams are expected to perform certain tasks at those stations. They will collect certain points when they perform the tasks. At the end of the event, the groups are expected to share the solution proposals and the problems they face. License not specified
__label__pos
0.795282
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute: Sign up Join the Stack Overflow community to: 1. Ask programming questions 2. Answer and help your peers 3. Get recognized for your expertise I'd like to add dots and lines to a video for each specific frame in Java. Can you give me some advice where I have to look for examples or libraries that could help me? I'm most familliar with Java but if you think e.g. Python works better, I'm going to try that. Overlaying an image at each frame at a specific position would be ok at first. Going further I'd like to draw dynamic lines at each frame. I can imagine that to be done by creating an image with the line and overlay that to the video frame. Thank you for your time. EDIT1: The format has to be somehow lossless because text has to stay readable, but I don't prefer any codec/container. EDIT2: I started using XUGGLE with this demo and it works. Does anyone know a better solution? share|improve this question      Are you hoping to decode individual frames from a file, overlay custom graphics, and re-encode the frames into a new video file? Are do you want to decode -> overlay -> present (play) to user? – Multimedia Mike Jun 2 '13 at 19:07      I'd like to store the modified file so there is no need for real time processing. – gro Jun 3 '13 at 7:37      And yes, decode -> overlay -> store is the way I'd like to go. – gro Jun 3 '13 at 7:43      Per your update, you have a working example but are seeking a "better" solution. Better in what way? – Multimedia Mike Jun 3 '13 at 21:14      In ways of performance or lines of code/simplicity for example. Although I'm ok with the solution I found myself. – gro Jun 4 '13 at 6:32 Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Browse other questions tagged or ask your own question.
__label__pos
0.663842
How to convert string to number in javascript or typescript How to convert string to number in js or typescript We can convert string to an integer or number with few different ways. In this article, we’ll see all different ways to convert string to number in javascript or typescript or in angular. Convert string to int typescript Here are the different methods to convert string to number. We’ll see an example of each methods. 1. Converting a string to number/integer using Native Number() function. 2. Converting a string to number/integer using parseInt() function. 3. Converting a string to number/integer using parseFloat() function. 4. Converting a string to number/integer using Math.floor() function. 5. Converting a string to number/integer using Math.round() function. 6. Converting a string to number/integer using Math.ceil() function. 7. Converting a string to number/integer by multiplying with 1. 8. Converting a string to number/integer using unary plus. Example for converting string to number We’ll see examples to convert string to number for all of the above methods. 1. Converting a string to number/integer using Native Number() function. Number() function convert the value of a string or other types to number type. If the value can’t be convert to number it’ll return NaN var test1 = "123"; console.log("Output of 123", Number(test1)); //Output of 123: 123 var test2 = "+123"; console.log("Output of +123: ", Number(test2)); //Output of +123: 123 var test3 = "-123"; console.log("Output of -123: ", Number(test3)); //Output of -123: -123 var test4 = "-123.45"; console.log("Output of -123.45: ", Number(test4)); //Output of -123.45: -123.45 var test5 = "+123.45"; console.log("Output of +123.45: ", Number(test5)); //Output of +123.45: 123.45 var test6 = "123XYZ"; console.log("Output of 123XYZ: ", Number(test6)); //Output of 123XYZ: NaN var test7 = undefined; console.log("Output of undefined: ", Number(test7)); //Output of undefined: NaN var test8 ="00123"; console.log("Output of 00123: ", Number(test8)); //Output of 00123: 123 var test9 = ""; console.log("Output of '': ", Number(test9)); //Output of '': 0 var test10 = null; console.log("Output of null: ", Number(test10)); //Output of undefined: NaN 2. Converting a string to number/integer using parseInt() function. The parseInt() function parses a string and returns an integer of the specified radix. If the first character cannot be converted to a number, NaN is returned. parseInt() method will parse the string value until a non-numeric character is encountered and then it will discard the remainder of the string and will return an integer value. Syntax : parseInt(string [, radix]) You can make use of the radix. The radix can be from 2 to 36. Use 2 for binary, 8 for octal, 10 for decimal & 16 for HexaDecimal number. Here we’ll use radix of 10, because radix of 10 converts from a decimal number. var test1 = "123"; console.log("Output of 123", parseInt(test1, 10)); //Output of 123: 123 var test2 = "+123"; console.log("Output of +123: ", parseInt(test2, 10)); //Output of +123: 123 var test3 = "-123"; console.log("Output of -123: ", parseInt(test3, 10)); //Output of -123: -123 var test4 = "-123.45"; console.log("Output of -123.45: ", parseInt(test4, 10)); //Output of -123.45: -123 var test5 = "+123.45"; console.log("Output of +123.45: ", parseInt(test5, 10)); //Output of +123.45: 123 var test6 = "123XYZ"; console.log("Output of 123XYZ: ", parseInt(test6, 10)); //Output of 123XYZ: 123 var test7 = undefined; console.log("Output of undefined: ", parseInt(test7, 10)); //Output of undefined: NaN var test8 ="00123"; console.log("Output of 00123: ", parseInt(test8, 10)); //Output of 00123: 123 var test9 = ""; console.log("Output of '': ", parseInt(test9, 10)); //Output of '': NaN var test10 = null; console.log("Output of null: ", parseInt(test10, 10)); //Output of undefined: NaN var test11 ="XYZ123"; console.log("Output of null: ", parseInt(test11, 10)); //Output of XYZ123: NaN Here in the above example, you can see for test4= "-123.45", it returns only the integer part of it which is -123. and for test6="123XYZ", parseInt() will parse the string until non-numeric character found and then it’ll discard rest of the string. so it’ll return 123 and for test11="XYZ123", the first character can not be converted to number so it’ll return NaN. console.log(parseInt("100")) //100 console.log(parseInt("100.5175")) //100 console.log(parseInt("10AA0.5175")) //10 console.log(parseInt("")) //NaN console.log(parseInt(null)) //NaN console.log(parseInt(Infinity)) //NaN console.log(parseInt(true)) //NaN console.log(parseInt(false)) //NaN console.log(parseInt("0x22")) //34 console.log(parseInt("0022")) //22 console.log(parseInt("0o51")) //0 console.log(parseInt("3.125e7")) //3 console.log(parseInt("35 35")) //35 console.log(parseInt("AB 35")) //NaN 3. Converting a string to number/integer using parseFloat() function. parseFloat() function parses a string and returns a floating point number. parseFloat() function checks if the first character in the specified string is a number. and If it is number, it parses the string until it encounters non-numeric character, and returns the number. Only the first number in the string is returned If the first character couldn’t be converted to a number, parseFloat() will returns NaN. Syntax : parseFloat(string) var test1 = "123"; console.log("Output of 123", parseFloat(test1)); //Output of 123: 123 var test2 = "+123"; console.log("Output of +123: ", parseFloat(test2)); //Output of +123: 123 var test3 = "-123"; console.log("Output of -123: ", parseFloat(test3)); //Output of -123: -123 var test4 = "-123.45"; console.log("Output of -123.45: ", parseFloat(test4)); //Output of -123.45: -123.45 var test5 = "+123.45"; console.log("Output of +123.45: ", parseFloat(test5)); //Output of +123.45: 123.45 var test6 = "123XYZ"; console.log("Output of 123XYZ: ", parseFloat(test6)); //Output of 123XYZ: 123 var test7 = undefined; console.log("Output of undefined: ", parseFloat(test7)); //Output of undefined: NaN var test8 ="00123"; console.log("Output of 00123: ", parseFloat(test8)); //Output of 00123: 123 var test9 = ""; console.log("Output of '': ", parseFloat(test9)); //Output of '': NaN var test10 = null; console.log("Output of null: ", parseFloat(test10)); //Output of undefined: NaN var test11 = "XYZ123"; console.log("Output of null: ", parseFloat(test11)); //Output of XYZ123: NaN var test12 = "00123.45XYZ"; console.log("Output of 00123.45XYZ: ", parseFloat(test12)); //Output of XYZ123: 123.45 Here in the above example, you can see for test4= "-123.45", it returns only the floating point number which is -123.45. and for test6="123XYZ", parseFloat() will parse the string until non-numeric character found and then it’ll discard rest of the string. so it’ll return 123 and for test11="XYZ123", the first character can not be converted to number so it’ll return NaN. and for test12 = "00123.45XYZ" parseFloat() will parse the string until non-numeric character found and then it’ll discard rest of the string. so it’ll return 123.45 console.log(parseFloat("100")) //100 console.log(parseFloat("100.5175")) //100.5175 console.log(parseFloat("10AA0.5175")) //10 console.log(parseFloat("")) //NaN console.log(parseFloat(null)) //NaN console.log(parseFloat(Infinity)) //Infinity console.log(parseFloat(true)) //NaN console.log(parseFloat(false)) //NaN console.log(parseFloat("0x22")) //0 console.log(parseFloat("0022")) //22 console.log(parseFloat("0o51")) //0 console.log(parseFloat("3.125e7")) //31250000 console.log(parseFloat("35 35")) //35 console.log(parseFloat("AB 35")) //NaN  4. Converting a string to number/integer using Math.floor() function. Math.floor() function returns largest integer less than or equal to the supplied value. So Math.floor() will be useful when you want to convert string to integer. Syntax : Math.floor(x) Here are few examples of it. var test1 = "123"; console.log("Output of 123: ", Math.floor(test1)); //"Output of 123: " 123 var test2 = "+123"; console.log("Output of +123: ", Math.floor(test2)); //"Output of +123: " 123 var test3 = "-123"; console.log("Output of -123: ", Math.floor(test3)); //"Output of -123: " -123 var test4 = "-123.45"; console.log("Output of -123.45: ", Math.floor(test4)); //"Output of -123.45: " -124 var test5 = "+123.45"; console.log("Output of +123.45: ", Math.floor(test5)); //"Output of +123.45: " 123 var test6 = "123XYZ"; console.log("Output of 123XYZ: ", Math.floor(test6)); //"Output of 123XYZ: " NaN var test7 = undefined; console.log("Output of undefined: ", Math.floor(test7)); //"Output of undefined: " NaN var test8 ="00123"; console.log("Output of 00123: ", Math.floor(test8)); //"Output of 00123: " 123 var test9 = ""; console.log("Output of '': ", Math.floor(test9)); //"Output of '': " 0 var test10 = null; console.log("Output of null: ", Math.floor(test10)); //"Output of undefined: " 0 var test11 = "XYZ123"; console.log("Output of null: ", Math.floor(test11)); //"Output of XYZ123: " NaN var test12 = "00123.45XYZ"; console.log("Output of 00123.45XYZ: ", Math.floor(test12)); //"Output of XYZ123: " NaN Here you can see in the above example for test4 = "-123.45", Math.floor() returns -124. Because -124 largest integer less than -123.45. 5. Converting a string to number/integer using Math.round() function. The Math.round() function returns the value of a number rounded to the nearest integer. Syntax : Math.round(x) var test1 = "123"; console.log("Output of 123: ", Math.round(test1)); //"Output of 123: " 123 var test2 = "+123"; console.log("Output of +123: ", Math.round(test2)); //"Output of +123: " 123 var test3 = "-123"; console.log("Output of -123: ", Math.round(test3)); //"Output of -123: " -123 var test4 = "-123.45"; console.log("Output of -123.45: ", Math.round(test4)); //"Output of -123.45: " -124 var test5 = "+123.45"; console.log("Output of +123.45: ", Math.round(test5)); //"Output of +123.45: " 123 var test6 = "123XYZ"; console.log("Output of 123XYZ: ", Math.round(test6)); //"Output of 123XYZ: " NaN var test7 = undefined; console.log("Output of undefined: ", Math.round(test7)); //"Output of undefined: " NaN var test8 ="00123"; console.log("Output of 00123: ", Math.round(test8)); //"Output of 00123: " 123 var test9 = ""; console.log("Output of '': ", Math.round(test9)); //"Output of '': " 0 var test10 = null; console.log("Output of null: ", Math.round(test10)); //"Output of undefined: " 0 var test11 = "XYZ123"; console.log("Output of null: ", Math.round(test11)); //"Output of XYZ123: " NaN var test12 = "00123.45XYZ"; console.log("Output of 00123.45XYZ: ", Math.round(test12)); //"Output of XYZ123: " NaN 6. Converting a string to number/integer using Math.ceil() function. The Math.ceil() function returns smallest integer greater than or equal to the given number. Syntax : Math.ceil(x) Few test results: var test1 = "123"; console.log("Output of 123: ", Math.ceil(test1)); //"Output of 123: " 123 var test2 = "+123"; console.log("Output of +123: ", Math.ceil(test2)); //"Output of +123: " 123 var test3 = "-123"; console.log("Output of -123: ", Math.ceil(test3)); //"Output of -123: " -123 var test4 = "-123.45"; console.log("Output of -123.45: ", Math.ceil(test4)); //"Output of -123.45: " -123 var test5 = "+123.45"; console.log("Output of +123.45: ", Math.ceil(test5)); //"Output of +123.45: " 124 var test6 = "123XYZ"; console.log("Output of 123XYZ: ", Math.ceil(test6)); //"Output of 123XYZ: " NaN var test7 = undefined; console.log("Output of undefined: ", Math.ceil(test7)); //"Output of undefined: " NaN var test8 ="00123"; console.log("Output of 00123: ", Math.ceil(test8)); //"Output of 00123: " 123 var test9 = ""; console.log("Output of '': ", Math.ceil(test9)); //"Output of '': " 0 var test10 = null; console.log("Output of null: ", Math.ceil(test10)); //"Output of undefined: " 0 var test11 = "XYZ123"; console.log("Output of null: ", Math.ceil(test11)); //"Output of XYZ123: " NaN var test12 = "00123.45XYZ"; console.log("Output of 00123.45XYZ: ", Math.ceil(test12)); //"Output of XYZ123: " NaN 7. Converting a string to number/integer by multiplying with 1. We can also convert string to number in typescript or javascript by multiplying number with 1. var test1 = "123"; console.log("Output of 123: ", test1*1); //"Output of 123: " 123 var test2 = "+123"; console.log("Output of +123: ", test2*1); //"Output of +123: " 123 var test3 = "-123"; console.log("Output of -123: ", test3*1); //"Output of -123: " -123 var test4 = "-123.45"; console.log("Output of -123.45: ", test4*1); //"Output of -123.45: " -123.45 var test5 = "+123.45"; console.log("Output of +123.45: ", test5*1); //"Output of +123.45: " 123.45 var test6 = "123XYZ"; console.log("Output of 123XYZ: ", test6*1); //"Output of 123XYZ: " NaN var test7 = undefined; console.log("Output of undefined: ", test7*1); //"Output of undefined: " NaN var test8 ="00123"; console.log("Output of 00123: ", test8*1); //"Output of 00123: " 123 var test9 = ""; console.log("Output of '': ", test9*1); //"Output of '': " 0 var test10 = null; console.log("Output of null: ",test10*1); //"Output of undefined: " 0 var test11 = "XYZ123"; console.log("Output of null: ", test11*1); //"Output of XYZ123: " NaN var test12 = "00123.45XYZ"; console.log("Output of 00123.45XYZ: ", test12*1); //"Output of XYZ123: " NaN 8. Converting a string to number/integer using unary plus. The another approach to convert string to number is using unary plus operator. It has better performance but lacks readability. var test1 = "123"; console.log("Output of 123: ", +test1); //"Output of 123: " 123 var test2 = "+123"; console.log("Output of +123: ", +test2); //"Output of +123: " 123 var test3 = "-123"; console.log("Output of -123: ", +test3); //"Output of -123: " -123 var test4 = "-123.45"; console.log("Output of -123.45: ", +test4); //"Output of -123.45: " -123.45 var test5 = "+123.45"; console.log("Output of +123.45: ", +test5); //"Output of +123.45: " 123.45 var test6 = "123XYZ"; console.log("Output of 123XYZ: ", +test6); //"Output of 123XYZ: " NaN var test7 = undefined; console.log("Output of undefined: ", +test7); //"Output of undefined: " NaN var test8 ="00123"; console.log("Output of 00123: ", +test8); //"Output of 00123: " 123 var test9 = ""; console.log("Output of '': ", +test9); //"Output of '': " 0 var test10 = null; console.log("Output of null: ",+test10); //"Output of undefined: " 0 var test11 = "XYZ123"; console.log("Output of null: ", +test11); //"Output of XYZ123: " NaN var test12 = "00123.45XYZ"; console.log("Output of 00123.45XYZ: ", +test12); //"Output of XYZ123: " NaN console.log(+"100") //100 console.log(+"100.5175") //100.5175 console.log(+"10AA0.5175") //NaN console.log(+"") //0 console.log(+" ") //0 console.log(+null) //0 console.log(+undefined) //Nan console.log(+Infinity) //Infinity console.log(+true) //1 console.log(+false) //0 console.log(+"0x22") //34 console.log(+"0022") //22 console.log(+"0o51") //41 console.log(+"3.125e7") //31250000 console.log(+"35 35") //NaN console.log(+"AB 35") //NaN Here in this table, you can see the output of different methods. xNumber(x)parseInt(x)parseFloat(x)Math.floor(x)Math.round(x)Math.ceil(x)x*1+x “123”123123123123123123123123 “+123”123123123123123123123123 “-123”-123-123-123-123-123-123-123-123 “123.45”123.45123123.45123123124123.45123.45 “-123.45”-123.45-123-123.45-124-123-123-123.45-123.45 “12e5”120000012120000012000001200000120000012000001200000 “12e-5”0.00012120.000120010.000120.00012 “0123”123123123123123123123123 “0000123”123123123123123123123123 “0b111”70077777 “0o10”80088888 “0xBABE”478064780604780647806478064780647806 “4294967295”42949672954294967295429496729542949672954294967295429496729542949672954294967295 “123456789012345678”123456789012345680123456789012345680123456789012345680123456789012345680123456789012345680123456789012345680123456789012345680123456789012345680 “12e999”Infinity12InfinityInfinityInfinityInfinityInfinityInfinity “”0NaNNaN00000 “123foo”NaN123123NaNNaNNaNNaNNaN “123.45foo”NaN123123.45NaNNaNNaNNaNNaN ” 123 “123123123123123123123123 “foo”NaNNaNNaNNaNNaNNaNNaNNaN “12e”NaN1212NaNNaNNaNNaNNaN “0b567”NaN00NaNNaNNaNNaNNaN “0o999”NaN00NaNNaNNaNNaNNaN “0xFUZZ”NaN150NaNNaNNaNNaNNaN “+0”00000000 “-0”00000000 “Infinity”InfinityNaNInfinityInfinityInfinityInfinityInfinityInfinity “+Infinity”InfinityNaNInfinityInfinityInfinityInfinityInfinityInfinity “-Infinity”-InfinityNaN-Infinity-Infinity-Infinity-Infinity-Infinity-Infinity null0NaNNaN00000 undefinedNaNNaNNaNNaNNaNNaNNaNNaN true1NaNNaN11111 false0NaNNaN00000 InfinityInfinityNaNInfinityInfinityInfinityInfinityInfinityInfinity NaNNaNNaNNaNNaNNaNNaNNaNNaN {}NaNNaNNaNNaNNaNNaNNaNNaN {valueOf: function(){return 42}}42NaNNaN4242424242 {toString: function(){return “56”}}5656565656565656 Taken From SO Answer: Converting a string to number Conclusion There are many ways to convert string to number in javascript/typescript but it’s upto the developer to choose the right approach based on performance or readability. I hope you like this article. Also Read:
__label__pos
0.996024
  It is currently Sat, 22 Jul 2017 16:40:06 GMT   Author Message  (IP_MULTICAST_IF) Multicast and Linux !? Hi there, is there anyone who can suggest me how to fix this problem? I've just tried to implement a client that send datagrams to a multicast address (224.0.0.11). Basically the source code you find below it's a function that creates a socket and set IP_MULTICAST_IF flag at the IP level of the socket. When a try to run it I get the following message: "initsocketss(): setsockopt IP_MULTICAST_IF failed: Cannot assign requested address" I read some messages in the newsgroup about people having the same problem, but I didn't find any answer. Other steps that I followed were: I'm using Linux Red Had 2.0.31 Do you have any idea about what I missed !? Thanx a lot. /Marco ________________________________________________________________________ void initsockets(){     struct ip_mreq imr;     int enable = 1;     imr.imr_multiaddr.s_addr = inet_addr(ALLMOBAGENTS);/* 224.0.0.11 */     /* If no interface is specified then        the interface leading to the default route is used.*/     imr.imr_interface = terminalIPaddress;     RegisterMesckt = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);     if (setsockopt(RegisterMesckt,SOL_SOCKET,SO_REUSEADDR,&enable,sizeof(int)) < 0){           printf ("Error setting REUSEADDR option \n");           exit(-1);     }     if (setsockopt(RegisterMesckt, IPPROTO_IP, IP_MULTICAST_IF                   (char *)&imr, sizeof(struct ip_mreq)) < 0)  {             perror("initsockets(): setsockopt IP_MULTICAST_IF failed");             exit(-1);     }  Sun, 03 Dec 2000 03:00:00 GMT     (IP_MULTICAST_IF) Multicast and Linux !? So what does your ifconfig report?  Mine reports flags as follows:           UP BROADCAST RUNNING ALLMULTI MULTICAST  MTU:1500  Metric:1 Is your kernel multicast-enabled?  If not, you will have to rebuild it:         CONFIG_IP_MULTICAST=y If your machine has 2 network cards and you want mcast groups on either side, you should also set:         CONFIG_IP_MROUTE=y ...but I could never get this to work properly, at least on 2.0.30 :-( (Although I posted to this group at the time, I got no response.  AFAIR my problem was that packets originating at the host were only sent out on one side although both sides contained group members.  Forwarding between the sides worked fine.) --Steve Stephen Crane, Dept of Computing, Imperial College of Science, Technology and Medicine, 180 Queen's Gate, London sw7 2bz, UK:jsc@{doc.ic.ac.uk, icdoc.uucp}  Mon, 04 Dec 2000 03:00:00 GMT         [ 2 post ]  Similar Threads 1. Linux multicast is slower than Windows multicast ? 2. IP_MULTICAST_IF: address not bound to any interface 3. setsockopt with IP_MULTICAST_IF option 4. multicasting tools on linux/unix 5. Linux IPv4 Multicast question 6. linux command to issue a join for a host participating in multicast grroup 7. Multicast stops working (timeout) on Linux router 8. Forwarding multicast packets in Linux, for different subnets. 9. Howto enable multicast forwarding on Linux 10. multicast routing with linux.   Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group. Designed by ST Software
__label__pos
0.800466
 Row Headers Nevron Open Vision Documentation Row Headers About Row Headers Row headers are button like elements that are represented by NRowHeader elements. The row headers are contained inside an instance of the NRowHeadersCollection, an instance of which is accessible from the RowHeaders property of NGrid. The following image illustrates row headers: The row headers serve the following purposes The visibility of the row headers is controlled by the Visible property. The following code snipped hides the row headers: Hide the row headers Copy Code grid.RowHeaders.Visible = false; Send Feedback
__label__pos
0.999478
<meta http-equiv="refresh" content="1; url=/nojavascript/"> Dismiss Skip Navigation You are viewing an older version of this Concept. Go to the latest version. Counting Events And' means multiply % Progress Practice Counting Events Practice Progress % Practice Now Multiplication Rule Objective Here you will learn how to quickly calculate the probability of the intersection of multiple independent events without building a frequency table. Concept Finding the probability of getting two or three heads in a row when flipping a fair coin is straightforward enough by building a frequency table. However, the process becomes somewhat unwieldy when the experiment is more complex, such as calculating the probability of pulling 3 queens in a row from a standard deck of cards. Building a frequency table for all 52 cards would be time consuming at best. There must be an easier way, right? Watch This http://youtu.be/Q_7PR9kRXWs StatsLectures – Multiplication Rule (Probability “and”) Guidance If I bet someone $1 that I can roll a standard die and get a 6, and then do roll the die and get a 6, I would probably get my $1, along with a clap on the back and a “congratulations!” from my friends. However, if I bet someone $20 that I can roll 20 times and get 6 every time, and then I do just that, I would probably be dealing with a very angry group of people who want to know how I cheated! That’s because it would be, at best, very improbable that I could get a series of 20 6’s in a row under normal circumstances. Let’s see if we can find out just how improbable. Let’s start with the probability of just one roll of a 6: Since there are 6 sides, the probability is: P(6)=\frac{1 \ outcome}{6 \ possible \ outcomes}=\frac{1}{6}\ or \ 16.7\% For two 6’s in a row: If we create a table of the possible rolls where the only total outcome yielding two 6’s is highlighted in blue, we get: KEY With this already pretty unwieldy table, we can see that there are 36 possible outcomes of rolling a standard die twice. Therefore, the probability of rolling two 6’s in a row is: P(two \ 6's)=\frac{1 \ outcome}{36 \ possible \ outcomes}=\frac{1}{36}\ or \ 2.8\% It should be apparent that things only get crazier from here, since calculating 3 6’s this way would require another row of 6 possibilities for each of the 36 outcomes of the 2 nd roll! However, look at the difference between the two probabilities: P(one \ 6)=\frac{1}{6}\ and \ P(two \ 6's)=\frac{1}{6}\times \frac{1}{6}=\frac{1}{36} The fact that the probability of getting two 6’s is  \frac{1}{6^{th}} of   \frac{1}{6} is no coincidence, of course. In fact, to understand how to calculate more complex intersections of independent compound probabilities, it may help to remember something you likely learned when practicing word problems: To translate English to math, the word of and the multiplication sign  · or  × mean the same thing. Since the probability of getting two 6’s in a row is  \frac{1}{6^{th}} \ of \ \frac{1}{6^{th}}  we can say: P(two \ 6's)=\frac{1}{6} \ of \ \frac{1}{6}=\frac{1}{6}\times \frac{1}{6}=\frac{1}{36} This is an example of the multiplication rule of compound probability: P(total)=P(1st \ outcome)\times P(2nd \ outcome)\ldots \times \ P(last \ outcome) Now we can actually calculate the probability of 20 6’s in a row: P(20 \ 6's)=\frac{1}{6}\times \frac{1}{6} \ldots \frac{1}{6}=\left(\frac{1}{6}\right)^{20}=\frac{1}{3,656,158,440,062,976} or approximately one in three and one-half quadrillion, which I would consider not good odds! Which also illustrates the practical impossibility of solving such a question with a frequency table, since it would take approximately 116,000,000 years just to write out the 6 th row at one number per second! (not to mention the 1 trillion sheets of paper \ldots ) Example A What would be the theoretical probability of randomly pulling a queen from a deck of 52 cards, putting it back, randomly pulling a queen again, and so on until you have pulled 5 queens in a row? Solution: The theoretical probability of pulling a single queen from a standard deck is: P(queen)=\frac{4 \ \text{queens}}{52 \ \text{cards}}=\frac{1}{13} \ or \ 7.7\% If we use the multiplication rule for five pulls, we get: \frac{1}{13}\times \frac{1}{13}\times \frac{1}{13}\times \frac{1}{13}\times \frac{1}{13}= \frac{1}{13^5}=\frac{1}{371293} Example B What is the theoretical probability of rolling a 1, 2, 3, 4, 5, and then 6, in order, on six successive rolls of a standard die? Solution: The probability of rolling any single number on a standard die is \frac{1}{6} . Use the multiplication rule: P(1-6)=\frac{1}{6} \times \frac{1}{6} \times \frac{1}{6} \times \frac{1}{6} \times \frac{1}{6} \times \frac{1}{6}=\frac{1}{6^6}=\frac{1}{46656} Example C What is the theoretical probability that you might deal the King of Hearts, Jack of Diamonds, and then any Ace, in order, from a standard deck of cards, assuming you replace each card after drawing? Solution: Let’s start by evaluating the individual probabilities. • P(first \ card)=\frac{\text{1 King of Hearts}}{\text{52 total cards}}=\frac{1}{52} • P(second \ card)=\frac{\text{1 Jack of Diamonds}}{\text{52 total cards}}=\frac{1}{52} • P(third \ card)=\frac{\text{4 Aces}}{\text{52 total cards}}=\frac{4}{52}=\frac{1}{13} Now we can use the multiplication rule: P(King \ of \ Hearts, \ Jack \ of \ Diamonds, \ Ace)=\frac{1}{52}\times \frac{1}{52} \times \frac{1}{13}=\frac{1}{35152} Concept Problem Revisited Finding the probability of getting two or three heads in a row when flipping a fair coin is straightforward enough by building a frequency table. However, the process becomes somewhat unwieldy when the experiment is more complex, such as calculating the probability of pulling 3 queens in a row from a standard deck of cards. Building a frequency table for all 52 cards would be time consuming at best. There must be an easier way, right? Of course, now you know this isn’t even really a question anymore, the multiplication rule makes this question pretty easy: P(3 \ queens)=\frac{1}{52}\times \frac{1}{51} \times\frac{1}{50}=\frac{1}{132600} Vocabulary The multiplication rule of probability states that, for independent events: P(total)=P(\text{case } 1)\times P(\text{case } 2)\ldots \times P(\text{case } n) Guided Practice 1. What is the probability of rolling an odd number, followed by an even number, followed by a prime number, on three successive rolls of a 20-sided die? 2. What is the probability of pulling a heart, replacing it, pulling a club, replacing it, pulling a diamond, replacing it, then pulling a spade, all from a standard deck? 3. What is the probability of flipping a coin ten times in a row, and getting heads every time? 4. What is the probability of spinning red 5 times in a row on a spinner with 6 equally spaced color segments, only one of which is red? Solutions: 1. Apply the multiplication rule: P(total) =P(\text{case} \ 1)\times P(\text{case} \ 2)\ldots \times P(\text{case} \ n) P(odd, \ even, \ prime) &=P(odd) \times P(even) \times P(prime)\\P(odd, \ even, \ prime) &=\frac{10}{20} \times \frac{10}{20} \times \frac{8}{20}=\frac{800}{8000}=\frac{1}{10} \ or \ 0.1 \ or \ 10\%\\P(odd, \ even,\ prime)&=10\% 2. We can apply the multiplication rule here also: P(heart,\ club,\ diamond,\ spade) &=\frac{1}{4} \times \frac{1}{4} \times \frac{1}{4} \times \frac{1}{4}=\frac{1}{256} \ or \ 0.00391 \ or \ .4\% \\P(heart, \ club, \ diamond, \ spade) &=0.4\% 3. Since we are looking for the same outcome from the same experiment repeated ten times, we can ‘shortcut’ the multiplication rule by using an exponent: P(heads \ ten \ times) &=\left(\frac{1}{2}\right)^{10}=\frac{1^{10}}{2^{10}}=\frac{1}{1024} \ or \ 0.001 \ or \ 0.1\% \\P(heads \ ten \ times) &=0.1\% 4. This one is similar to the last, in that we are looking for the same outcome of the same experiment, multiple times (5 times, in this case). P(red \ five \ times) &=\left(\frac{1}{6}\right)^5=\frac{1^5}{6^5}=\frac{1}{7776} \ or \ 0.0001 \ or \ 0.01 \% \\P(red \ five \ times) &=0.01\% Practice 1. What are independent events? 2. What is the multiplication rule? Questions 3-7: Suppose you have an opaque bag filled with 6 red, 4 green, 7 blue and 5 purple balls. 3. What is the probability of randomly pulling a purple ball from the bag, returning it, and pulling a purple ball again on your second pull? 4. What is the probability of randomly pulling a red ball from the bag, returning it, and pulling ablue ball on your second pull? 5. What is the probability of randomly pulling a green ball from the bag, returning it, and pulling agreen ball again on your second pull? 6. What is the probability of randomly pulling a blue ball from the bag, returning it, and pulling ared ball on your second pull? 7. What is the probability of randomly pulling a purple ball from the bag, returning it, and pulling ablue ball on your second pull? Questions 8 – 12: Suppose you have two standard dice, one red and one blue. 8. What is the probability of rolling a 3 on the red die and a 5 on the blue one? 9. What is the probability of rolling a 3 or 4 on the red die and a 5 on the blue one? 10. What is the probability of rolling an even number on the red die and an odd on the blue one? 11. What is the probability of rolling a 6 on the red die and an odd number on the blue one? 12. What is the probability of rolling a 1 on the red die and prime number on the blue one? Questions 13 – 16: Suppose you are dealing with a standard deck of cards, calculate the probability of each outcome as described, assuming you replace each card after drawing it. 13. Pulling a queen, then any club, then any red card. 14. Pulling the Ace of Spades, then a red 6, then any king. 15. Pulling any face card three times in a row. 16. Pulling a face card, then an ace, then the 5 of clubs. Vocabulary multiplication rule of probability multiplication rule of probability The multiplication rule of probability states that, for independent events: P(total) = P(Case 1) x P(Case 2) x ... P(Case n). Image Attributions Reviews Please wait... Please wait... Original text
__label__pos
1
Open Source RDBMS - Seamless, Scalable, Stable and Free 한국어 | Login |Register Current Events Join our developers event to win one of the valuable prizes! posted 2 years ago viewed 9688 times Share this article 20 Minutes to Understanding Spatial Database spacial-database.png Spatial RDBMS is an RDBMS that can process spatial data. Popular RDBMSs, such as Oracle, offer their own Spatial RDBMS features or add-ons so that spatial data can be processed. Since each DBMS has a different architecture, it is difficult to show how it operates through a simple diagram. But we can explain at least the concept of a spatial DBMS through the following diagram. conceptual-diagram-of-a-spatial-rdbms.png Spatial RDBMS allows to use SQL data types, such as int and varchar, as well as spatial data types, such as Point, Linestring and Polygon for geometric calculations like distance or relationships between shapes. RDBMS uses the B-Tree series or Hash Function to process indexes (see CUBRID Query Tuning Techniques for more explanation), basically to determine the size or redundancies of column values. In other words, only one-dimensional data can be processed. Since spatial data types are two or three dimensional: 1. R-Tree series or Quad Trees can be used in Spatial RDBMS to process such data; 2. Or it is necessary to transform two or three dimensional data to one dimensional data, then B-Tree can be used. Many benefits follow if the existing RDBMS is extended to process spatial data. First, even when conducting geo-spatial tasks, there will be many occasions when basic data types, such as numbers or characters, are used. Another benefit is that there will not be a burden of additional training, since SQL is already a verified solution which can successfully store the data. RDBMS is not the only database management system available. Likewise, spatial RDBMS is not the only spatial database management system available. Many databases, such as MongoDB, the document-oriented database, search engines such as Lucene or Solr, provide spatial data processing features. However, these solutions offer less features and do not provide high precision calculations. To understand what high precision calculations mean, we will take a closer look at the features a spatial DBMS provides. OpenGIS OpenGIS is a standard solution to process spatial data. The OGC (Open Geospatial Consortium), a consortium made up of 416 governmental organizations, research centers and companies from all over the world (as of 2011), legislates this standard. OpenGIS (Open Geodata Interpretability Specification) is a registered trademark of the OGC, and is a standard for geospatial data processing (this document does not differentiate spatial and geospatial). Out of the many standards in the OpenGIS, the one standard needed to understand the spatial DBMSS is Simple Feature. Simple Feature As mentioned above, Simple Feature is a standard needed to process the geospatial data. Geometry Object Model (spatial data type), Spatial Operation and Coordinate System (two and three dimension) are subject to the Simple Feature standard. Geometry Object Model are figures such as Point, LineString and Polygon. geometry-object-model-examples.png The Geometry Data Model (spatial data type) can exist in not only two dimensions but three dimensions as well. The area dealt by Simple Feature is Euclid. Therefore, spatial operation on intersects and touches are all Euclid geometry areas. In the Simple Feature Statement document, the Geometry Object Model is dealt like an Object-Oriented languages class. An actual UML is used to describe. The following is a Geometry Object Model Class Diagram, which provides a summary of the contents in a Simple Feature Specification. Point, LineString, and Polygon, all inherit this geometry. ‘Query’ and ‘analysis’ blocks are Spatial Operations. + dimension() : Integer + coordinateDimension() : Integer + spatialDimension() : Integer + geometry Type() : String + SRID() : Integer + envelope() : Geometry #query + equals(another :Geometry) : Boolean + disjoint(another :Geometry) : Boolean + intersects(another :Geometry) : Boolean + touches(another :Geometry) : Boolean + crosses(another :Geometry) : Boolean + within(another :Geometry) : Boolean + contains(another :Geometry) : Boolean ... #analysis + distance(another : Geometry) : Distance + buffer(another : Distance) : Geometry + convexHull() : Geometry ... The standards document uses a formula to describe the operation. a-within-b.png The Within calculation shown in the above Figure can be explained in the following formula where I() function is interiorE() function is exterior. (a ? b = a) ? (I(a) ? E(b)) = Ø ) Operations such as buffer() are used frequently. When a point unit geometry is given as an argument, then this is processed by buffer() and returned as a geometry that is in a form of a line that is surrounded for a certain distance. Buffer() for point would be a circle. If the center of a road is shown with a LineString, the buffer() can be used to identify the road type that can put the road width into consideration. Building near a certain road can be identified using touches(). The Simple Feature described so far is the "Simple Feature Common Architecture". The other Simple Feature standards are Simple Feature CORBA, Simple Feature OLE/COM and Simple Feature SQL. Naturally, Spatial RDBMS is closely related to Simple Feature SQL. Simple Feature SQL includes Simple Feature Common Architecture, and deals with the standards Spatial RDBMS must have based on ANSI SQL 92. It deals with how to show the Geometry Object Model in DBMS data type and how to show the SQL function in spatial operation, etc. It also specifies the basic DBMS Table the Spatial DBMS must have. SPATIAL_REF_SYS, a table that contains the Spatial Reference ID is a good example. A famous open source library that implements the Simple Feature specifications is JTS Topology Suite, which is written in a Java, and GEOS, a C++ port of JTS. GEOS is used in PostGIS (package that is added on to the PostgreSQL to process Spatial data). Spatial Reference Explanations or figures regarding Spatial Reference is from http://www.sharpgis.net/post/2007/05/Spatial-references2c-coordinate-systems2c-projections2c-datums2c-ellipsoids-e28093-confusing.aspx. Spatial DBMS is most widely used in areas such as transportation (air/shipping) and astronomy. The calculation used for oil-pump construction and to set flight courses can be explained in geometric terms as calculating the length of a line that is connected from one dot to the other on the Earth’s surface. Locations on the Earth’s surface is usually marked using the longitude and latitude. geographical-coordinate-system.png As seen in the above figure, a one degree longitude difference differs greatly depending on the latitude. A longitude 1° from the equator is 111.321 km, but longitude 1° from latitude 60° is only 55.802 km. A three dimensional Earth surface layout must be modified to a two dimensional map for easy calculation of width and distance. This is called projection. However, it’s almost impossible to show a round Earth in a two dimensional form so that it is both precise and simple. The most famous map in the world, the Mercator Projection, is suitable for nautical purposes. The angles of the circular Earth are identically portrayed in a flat surface. Therefore, the image is larger than it actually is near the pole areas. mercator-projection.png Plate Carrée Projection (also known as Equirectangular Projection) is better than Mercator Projection when calculating lengths or widths. equirectangular-projection.png As the figure above shows, the location is projected with a square grid. Therefore, the calculation of distance from north, south, east and west is extremely precise. Plate Carrée Projection is currently used as the de facto method in the GIS area and has been adopted by the Google Earth service. However, we still have to find the longitude and latitude. As shown in Geographical Coordinate System figure, we need to know where the center of the Earth is to calculate the longitude and latitude using the meridian. earth-is-lumpy.jpg The Earth is neither globular nor oval. On top of that, the Earth surface’s position shifts due to the Earth crust’s movement. The Earth surface moves 1cm every year, even without a severe earthquake. Therefore, the center of the Earth always changes. The difference in distance between the center of a virtual globe and the center of the ever-changing oval globe is called the Geocentric Datums, or just Datums. geocentric-datums.png Although the location is identical on the surface, the longitude and latitude values can change depending on the Datums. The Datums currently most widely used as a “standard” is the value determined by the WGS84 (World Geodetic System), which is the standard method used in GPS. Spatial Reference is a combination of the coordination system, projection and datum which has been explained up until now. The EPSG (European Petroleum Survey Group) created an ID system for the coordination system, projection and datum. When we say the EPSG:4326 is used as a spatial reference, we mean that the Plate Carrée Projection is used with the longitude/latitude value based on WGS84. EPSG:4326 is a spatial reference used for GPS satellites and NATO military purposes, and is most widely used in the world. In the above Geometry Object Model Class Diagram, the Class Diagram contains a method SRID(), which returns this spatial reference ID. Distance and width calculation is done based on spatial reference. In order to conduct a spatial operation on a geometry model with different spatial reference IDs (SRID), one of the two must be changed to the other’s SRID. In a special DBMS that goes by the Simple Feature standard, this SRID is saved in the SPATIAL_REF_SYS table. There are more than 3,000 SRIDs. http://spatialreference.org/ref/?search=korea shows SRIDs of the Korean Peninsula. Example of Spatial SQL The following example shows the Nearest Neighbor search, which can find N number of users within an M meter radius from a specific user’s location, made with a Spatial SQL. Let’s say that the userLocation table contains a field called user ID, which uses a character string, and location, which uses the point data type to show the location. If all location fields in the userLocation table uses the same SRID, then the Nearest Neighbor search can be executed easily, as shown in the following code snippet (this SQL example is active in PostgreSQL/PostGIS). Functions that start with ST_ is a spatial type and is the standard function defined in Simple Features. SELECT SIEVE.userID, SIEVE.DISTANCE as distance FROM (SELECT USERS.userID, USERS.location , ST_Distance (SPOT.location::geography, USERS.location:: geography) as DISTANCE FROM userLocation AS USERS, (SELECT location FROM userLocation WHERE userID = #userID#) AS SPOT WHERE USERS.userID != #userID# and ST_DWithin(SPOT.location, USERS.location, #diameter# ,false ) ) AS SIEVE ORDER BY SIEVE.DISTANCE limit #howMany# Representative Spatial RDBMS The most representative spatial RDBMS are, and PostgreSQL for open source RDBMS, and MS SQL Server and Oracle for commercial DBMS. Function-wise, there are three strong RDBMSs (PostgreSQL, Oracle, MS SQL Server) and one medium (MySQL). (Test results can be found here and here.) MyISAM must be used as a pool when using the Spatial Extension in MySQL. While PostgreSQL/PostGIS supports more than 300 Simple Feature functions and operators, MySQL provides only a few functions that uses MBR (Minimum Bound Rectangle). Since Oracle took over MySQL, no additional developments of Spatial Extension have progressed. The MS SQL Server provides the spatial function in the release and does not require a separate add-on. Therefore, departments that use a version above MS SQL 2008 can use the spatial function without a separate procedure. Oracle provides two separate spatial functions; Oracle Locator and Oracle Spatial. Oracle Spatial is the higher function and does not require additional license purchase in an environment that uses Enterprise Oracle. Spatial Index In the Spatial Index, the MBR (Minimum Bound Rectangle), also known as bounding box or envelope, is sought after in order to index the spatial data type. As shown in Figure 3, the Simple Feature requires all spatial data to provide a method that returns MBR. 2-deminsional-mbr.png 3-deminsional-mbr.png MBR is also used when two spatial data is combined ((MINX MINY, MAXX MINY, MAXX MAXY, MINX MAXY, MINX MINY)). Equivalence/size relationships in one-dimension can be expressed in space as intersect, cross, within or touches, and MBR is to be used to effectively process the relationship. When calculating relationships (intersects, touches, etc.) on two or more spatial data, use the MBR for linear computing. r-tree-configuration.png The figure above illustrates an R-Tree configuration with 4 sequences. The MBR that covers the spatial data is D to M and MBR created for indexing is A to C. Let’s create an example where spatial data, which includes a random point, is searched. If the point is in a “within” relationship with D, G or M, then the root to leaf node can be found immediately. If the point is in the area F and J intersects, then in the root node, A will be visited first then return F, then move to root node, select C and return J. This is where the problem lies. The example in Figure 2 only has two tree levels. However, it will take a lot of time to search the tree if there is a lot of data. These problems have been resolved in R+-Tree. r+tree-configuration.png In the figure above, the spatial data configuration from D to M is the same as in R Tree configuration. However, the A and C MBR area is different. In R+-Tree, if needed, the overlapping areas in the same level can be brought from different nodes. You can see that J and D are redundant. When such redundancies occur, when looking for the area F and J are intersecting, you need only to search in A MBR and do not have to search C. When Contemplating the Application of Spatial RDBMS In order to use the location based service using Spatial RDBMS, check whether the Spatial RDBMS satisfies the performance the service needs. MySQL needs to be checked to see whether the necessary functions are provided, but PostgreSQL/PostGIS does not require an examination. When implementing the Nearest Neighbor search with Spatial DBMS, the R-Tree index will contain numerous Point data that shows where the user location is. In order to search a user (Point) who is within an “N” meter radius of a specific location, acquire an MBR for the “N” meter (circle) radius and search the point the MBR is “within” from the root node. If many MBRs in the leaf node overlap, then more time is needed for the search. (Not all Spatial RDBMS uses R-Tree series as index. MS SQL Server uses Z-order enumeration to change spatial data to one-dimensional data, and indexes using B-Tree. IBM DB2 uses QuadTree.) Since RDBMS has to guarantee durability, logs are left on the disk for every operation, which places a severe load on the I/O. The RDBMS’s greatest fault is in the scalability. Spatial RDBMS is not adequate if multiple users have to process in real-time at the same time. Key-value DB that guarantees scalability uses the hash function as the index, so it is vulnerable when searching ranges (there is no key-value DB that offers spatial index yet). Mongo DB or Lucene has greater IO performance than RDBMS (durability not guaranteed), but they use only the most basic spatial index, and the functions are poor. If there is a limitation in the number of spatial data or operation, or already using MS SQL Server 2008, MySQL 5.1 above MyISAM, then the Spatial RDBMS would be a practical choice since there is no burden of adding additional platform infra. By Ki-sun Song, Web Platform Development Lab, NHN Corporation. comments powered by Disqus
__label__pos
0.808543
ferenda.sources.general.Sitenews – Generate a set of news documents from a single text file class ferenda.sources.general.Sitenews(config=None, **kwargs)[source] Generates a set of news documents from a single text file. This is a simple way of creating a feed of news about the site itself, with permalinks for individual posts and a Atom feed for subscribing in a feed reader. The text file is loaded by ferenda.ResourceLoader, so it can be placed in any resource directory for any repo used. By default, the resource name is “static/sitenews.txt” but this can be changed with config.newsfile The text file should be structured with each post/entry having a header line, followed by a empty line, then the body of the post. The body ends when a new header line (or EOF) is encountered. The header line should be formatted like <ISO 8859-1 datetime> <Entry title>. The body should be a regular HTML fragment.
__label__pos
0.581506
1. callmekatootie 2. CherryPy Commits Christian Wyglendowski  committed c63bb45 Fixed an issue with wrapping plain WSGI callables and removed some pre-remix code. • Participants • Parent commits e7330b8 • Branches cp3-wsgi-remix Comments (0) Files changed (3) File _cprequest.py View file • Ignore whitespace # Get the 'Host' header, so we can do HTTPRedirects properly. self.process_headers() - if self.app is None: - # Some interfaces (like WSGI) may have already set self.app. - # If not, look up the app for this path. - self.script_name = r = cherrypy.tree.script_name(self.path) - if r is None: - raise cherrypy.NotFound() - self.app = cherrypy.tree.apps[r] - else: - self.script_name = self.wsgi_environ.get('SCRIPT_NAME', '') + self.script_name = self.wsgi_environ.get('SCRIPT_NAME', '') # path_info should be the path from the # app root (script_name) to the handler. File _cptree.py View file • Ignore whitespace app = Application(app, script_name, conf) # Handle WSGI callables elif callable(app) and wrap: - app = HostedWSGI(app) + app = Application(HostedWSGI(app), script_name, conf) # In all other cases leave the app intact (no wrapping) self.apps[script_name] = app File _cpwsgi.py View file • Ignore whitespace self._cp_config = {'tools.wsgiapp.on': True, 'tools.wsgiapp.app': app, } - - def __call__(self, environ, start_response): - return self.app(environ, start_response) + # Server components #
__label__pos
0.981485