Place the rendered cells onto the page canvas and draw borders around
        them.
180923
def _place_rows_and_render_borders(container, rendered_rows):
        """"""
        def draw_cell_border(rendered_cell, cell_height, container):
            cell_width = rendered_cell.width
            background = TableCellBackground((0, 0), cell_width, cell_height,
                                             parent=rendered_cell.cell)
            background.render(container)
            for position in ('top', 'right', 'bottom', 'left'):
                border = TableCellBorder(rendered_cell, cell_height, position)
                border.render(container)
            return background

        y_cursor = container.cursor
        for r, rendered_row in enumerate(rendered_rows):
            container.advance(rendered_row.height)
            if rendered_row.index == 0:
                container.register_styled(rendered_row.row.section)
            container.register_styled(rendered_row.row)
            for c, rendered_cell in enumerate(rendered_row):
                cell_height = sum(rendered_row.height for rendered_row in
                                  rendered_rows[r:r + rendered_cell.rowspan])
                x_cursor = rendered_cell.x_position
                y_pos = float(y_cursor + cell_height)
                cell_container = VirtualContainer(container)
                background = draw_cell_border(rendered_cell, cell_height,
                                              cell_container)
                cell_container.place_at(container, x_cursor, y_pos)
                vertical_align = rendered_cell.cell.get_style('vertical_align',
                                                              container)
                if vertical_align == VerticalAlign.TOP:
                    vertical_offset = 0
                elif vertical_align == VerticalAlign.MIDDLE:
                    vertical_offset = (cell_height - rendered_cell.height) / 2
                elif vertical_align == VerticalAlign.BOTTOM:
                    vertical_offset = (cell_height - rendered_cell.height)
                y_offset = float(y_cursor + vertical_offset)
                rendered_cell.container.place_at(container, x_cursor, y_offset)
                container.register_styled(background)
            y_cursor += rendered_row.height
211381
private void drawElements(Bbox bounds, String url) {
		if (bounds != null && url != null) {
			drawRedRectangle(bounds, container);
			drawImageFromUrl(url, bounds, container);
		}
	}
49349
public function applyRowBorderToCell()
    {
        if (isset($this->row_styles["border-width"]) && $this->row_styles["border-width"]) {
            $cellstyle = $this->cell_styles["border-width"];
            if (!$cellstyle) {
                $cellstyle = $this->allcell_styles["border-width"];
            }
            $rowstyle = $this->row_styles["border-width"];
            if (!strstr($cellstyle, "T") && strstr($rowstyle, "T")) {
                $cellstyle .= "T";
            }

            if (!strstr($cellstyle, "B") && strstr($rowstyle, "B")) {
                $cellstyle .= "B";
            }

            if ($this->no_columns_printed == 1) {
                if (!strstr($cellstyle, "L") && strstr($rowstyle, "L")) {
                    $cellstyle .= "L";
                }

            }
            if ($this->no_columns_printed == $this->no_columns_to_print) {
                if (!strstr($cellstyle, "R") && strstr($rowstyle, "R")) {
                    $cellstyle .= "R";
                }

            }
            end($this->stylestack["border-width"]);
            $this->stylestack["border-width"][key($this->stylestack["border-width"])] = $cellstyle;
        }
    }
840698
def draw(self):
        """"""

        self.context.set_source_rgb(*self._get_background_color())
        self.context.rectangle(*self.rect)
        self.context.fill()

        # If show frozen is active, show frozen pattern
        if self.view_frozen and self.cell_attributes[self.key]["frozen"]:
            self._draw_frozen_pattern()
1350367
def render_sheet(range, batch, sheet)
      sheet_width = (sheet.columns * (@width + 2 * sheet.gap - 2 * sheet.trim)) + (2 * sheet.margin)
      sheet_height = (sheet.rows * (@height + 2 * sheet.gap - 2 * sheet.trim)) + (2 * sheet.margin)
      cc = Cairo::Context.new(Cairo::ImageSurface.new(sheet_width, sheet_height))
      num_this_sheet = 0
      sheet_num = 0
      y = sheet.margin
      x = sheet.rtl ? (sheet_width - sheet.margin - sheet.gap - @width) : sheet.margin
      @progress_bar.start("Saving PNG sheet to #{batch.summary}", @cards.size + 1) do |bar|
        range.each do |i|
          if num_this_sheet >= (sheet.columns * sheet.rows) # new sheet
            filename = batch.full_filename(sheet_num)
            cc.target.write_to_png(filename)
            new_sheet = false
            num_this_sheet = 0
            sheet_num += 1
            y = sheet.margin
            x = sheet.rtl ? (sheet_width - sheet.margin - sheet.gap - @width) : sheet.margin
            cc = Cairo::Context.new(Cairo::ImageSurface.new(sheet_width, sheet_height))
          end
          surface = trim(@cards[i].cairo_surface, sheet.trim, @width, @height)
          cc.set_source(surface, x, y)
          cc.paint
          num_this_sheet += 1
          x += (surface.width + sheet.gap) * (sheet.rtl ? -1 : 1)
          if num_this_sheet % sheet.columns == 0 # new row
            x = sheet.rtl ? (sheet_width - sheet.margin - sheet.gap - @width) : sheet.margin
            y += surface.height + sheet.gap
          end
          bar.increment
        end
        cc.target.write_to_png(batch.full_filename(sheet_num))
      end
    end
1161046
def draw(self):
        
        if self.state > 0:
            self.renderer.draw_background(self.surface, self.layout.position, self.layout.size)
            for row in self.layout.rows:
                for key in row.keys:
                    self.renderer.draw_key(self.surface, key)
346510
function renderCanvas(document) {
    var map = document.mindmap;
    var root = prepareNodes(map);
    var dimensions = getMindMapDimensions(root);

    var width = dimensions.width;
    var height = dimensions.height;
    $canvas.attr({
      width : width,
      height : height
    });

    ctx.textBaseline = "top";
    ctx.textAlign = "center";

    // fill background white
    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, width, height);

    ctx.translate(width / 2, height / 2);

    // render in two passes: 1. lines, 2. captions. because we have
    // no z-index, captions should not be covered by lines
    drawLines(root);
    drawCaptions(root);

    /**
     * Draws all branches
     */
    function drawLines(node, parent) {
      ctx.save();
      var x = node.offset.x;
      var y = node.offset.y;
      ctx.translate(x, y);

      // branch
      if (parent) {
        drawBranch(node, parent);
      }

      // bottom border
      if (!node.isRoot()) {
        ctx.fillStyle = node.branchColor;
        var tm = node.textMetrics;
        ctx.fillRect(0, tm.height + padding, tm.width, node.lineWidth);
      }

      node.forEachChild(function(child) {
        drawLines(child, node);
      });

      ctx.restore();
    }

    /**
     * Draws all captions.
     * 
     * @param node
     */
    function drawCaptions(node) {
      ctx.save();
      var x = node.offset.x;
      var y = node.offset.y;
      ctx.translate(x, y);

      var tm = node.textMetrics;
      var caption = node.getCaption();
      var font = node.text.font;

      // ctx.strokeStyle = "#CCC";
      // ctx.strokeRect(0, 0, tm.width, tm.height);

      ctx.font = font.style + " " + font.weight + " " + font.size
          + "px sans-serif";

      var captionX = tm.width / 2;
      var captionY = 0;
      if (node.isRoot()) {
        // TODO remove magic numbers
        captionX = 0;
        captionY = 20;

        // root box
        ctx.lineWidth = 5.0;
        ctx.strokeStyle = "orange";
        ctx.fillStyle = "white";
        mindmaps.CanvasDrawingUtil.roundedRect(ctx,
            0 - tm.width / 2 - 4, 20 - 4, tm.width + 8,
            tm.height + 8, 10);
      }

      ctx.strokeStyle = font.color;
      ctx.fillStyle = font.color;

      // TODO underline manually. canvas doesnt support it
      // TODO strike through manually

      function checkLength(str) {
        var ctm = ctx.measureText(str);
        return ctm.width <= tm.width;
      }

      // write node caption.

      if (checkLength(caption)) {
        // easy part only one line
        ctx.fillText(caption, captionX, captionY);
      } else {
        /**
         * caption consists of multiple lines. needs special handling
         * that imitates the line breaking algorithm "word-wrap:
         * break-word;"
         * 
         * <pre>
         * 1. break up string into words
         * 2. cut words that are too long into smaller pieces so they fit on a line
         * 3. construct lines: fit as many words as possible on a line
         * 4. print lines
         * </pre>
         */

        /**
         * step 1
         */
        // check all words and break words that are too long for a one
        // line
        // TODO not perfect yet
        // find words in string (special treatment for hyphens)
        // a hyphen breaks like a white-space does
        // var regex = /(\w+-+)|(\w+)|(-+)/gi;
        // var regex = /[^- ]+[- ]*/gi;
        // var regex = /[^ -]+-* *|[- ]+/gi;
        // for now just match for words and the trailing space
        // hyphenating has probably be done in step 2
        var regex = /[^ ]+ */gi;
        var words1 = caption.match(regex);
        console.log("words1", words1);

        /**
         * step 2
         */
        var words2 = [];
        words1.forEach(function(word) {
          if (!checkLength(word)) {
            var part = "";
            for ( var i = 0; i < word.length; i++) {
              var c = word.charAt(i);
              if (checkLength(part + c)) {
                part += c;
                continue;
              } else {
                words2.push(part);
                part = c;
              }
            }
            words2.push(part);
          } else {
            words2.push(word);
          }
        });

        console.log("words2", words2);

        /**
         * step 3
         */
        var wordWidth = function(str) {
          return ctx.measureText(str).width;
        };

        var lines = [];
        var line = "";
        var lineWidth = tm.width;

        // construct invidual lines
        words2.forEach(function(word) {
          if (line === "") {
            line = word;
          } else {
            if (wordWidth(line + " " + word) > lineWidth) {
              lines.push(line);
              line = word;
            } else {
              line += " " + word;
            }
          }
        });
        lines.push(line);
        console.log("lines", lines);

        /**
         * step 4
         */
        // print lines
        for ( var j = 0; j < lines.length; j++) {
          var line = lines[j];
          ctx.fillText(line, captionX, captionY + j * font.size);
        }
      }

      node.forEachChild(function(child) {
        drawCaptions(child);
      });

      ctx.restore();
    }
  }
1320591
def onMargins(self, left=0.1, top=0.1, right=0.1, bottom=0.1):
        
        bconf = self.panel_bot.conf
        l, t, r, b = bconf.margins
        bconf.set_margins(left=left, top=t, right=right, bottom=b)
        bconf.canvas.draw()
674481
def create_sheet(self):
        '''
        
        '''
        #--------------------------------
        # orient.txt supports many other headers
        # but we will only initialize with
        # the essential headers for
        # sample orientation and headers present
        # in existing demag_orient.txt file
        #--------------------------------


        #--------------------------------
        # create the grid
        #--------------------------------

        samples_list = list(self.orient_data.keys())
        samples_list.sort()
        self.samples_list = [ sample for sample in samples_list if sample is not "" ]
        #self.headers.extend(self.add_extra_headers(samples_list))
        display_headers = [header[1] for header in self.headers]
        self.grid = magic_grid.MagicGrid(self.panel, 'orient grid',
                                         self.samples_list, display_headers)
        self.grid.InitUI()

        #--------------------------------
        # color the columns by groups
        #--------------------------------

        for i in range(len(self.samples_list)):
            self.grid.SetCellBackgroundColour(i, 0, "LIGHT GREY")
            self.grid.SetCellBackgroundColour(i, 1, "LIGHT STEEL BLUE")
            self.grid.SetCellBackgroundColour(i, 2, "YELLOW")
            self.grid.SetCellBackgroundColour(i, 3, "YELLOW")
            self.grid.SetCellBackgroundColour(i, 4, "PALE GREEN")
            self.grid.SetCellBackgroundColour(i, 5, "PALE GREEN")
            self.grid.SetCellBackgroundColour(i, 6, "KHAKI")
            self.grid.SetCellBackgroundColour(i, 7, "KHAKI")
            self.grid.SetCellBackgroundColour(i, 8, "KHAKI")
            self.grid.SetCellBackgroundColour(i, 9, "KHAKI")
            self.grid.SetCellBackgroundColour(i, 10, "KHAKI")
            self.grid.SetCellBackgroundColour(i, 11, "LIGHT MAGENTA")
            self.grid.SetCellBackgroundColour(i, 12, "LIGHT MAGENTA")


        #--------------------------------
        # fill data from self.orient_data
        #--------------------------------

        headers = [header[0] for header in self.headers]
        for sample in self.samples_list:
            for key in list(self.orient_data[sample].keys()):
                if key in headers:
                    sample_index = self.samples_list.index(sample)
                    i = headers.index(key)
                    val = str(self.orient_data[sample][key])
                    # if it's a pmag_object, use its name
                    try:
                        val = val.name
                    except AttributeError:
                        pass
                    if val and val != "None":
                        self.grid.SetCellValue(sample_index, i, val)

        #--------------------------------

        #--------------------------------
        # fill in some default values
        #--------------------------------
        for row in range(self.grid.GetNumberRows()):
            col = 1
            if not self.grid.GetCellValue(row, col):
                self.grid.SetCellValue(row, col, 'g')

        #--------------------------------

        # temporary trick to get drop-down-menus to work
        self.grid.changes = {'a'}

        self.grid.AutoSize()
        #self.drop_down_menu = drop_down_menus.Menus("orient", self, self.grid, '')
        self.drop_down_menu = drop_down_menus3.Menus("orient", self.contribution, self.grid)
        self.Bind(wx.grid.EVT_GRID_LABEL_LEFT_CLICK, self.onLeftClickLabel, self.grid)
390094
def _draw_cursor(self, dc, grid, row, col,
                     pen=None, brush=None):
        """"""

        # If in full screen mode draw no cursor
        if grid.main_window.IsFullScreen():
            return

        key = row, col, grid.current_table
        rect = grid.CellToRect(row, col)
        rect = self.get_merged_rect(grid, key, rect)

        # Check if cell is invisible
        if rect is None:
            return

        size = self.get_zoomed_size(1.0)

        caret_length = int(min([rect.width, rect.height]) / 5.0)

        color = get_color(config["text_color"])
        if pen is None:
          pen = wx.Pen(color)
        if brush is None:
          brush = wx.Brush(color)

        pen.SetWidth(size)

        # Inner right and lower borders
        border_left = rect.x + size - 1
        border_right = rect.x + rect.width - size - 1
        border_upper = rect.y + size - 1
        border_lower = rect.y + rect.height - size - 1

        points_lr = [
            (border_right, border_lower - caret_length),
            (border_right, border_lower),
            (border_right - caret_length, border_lower),
            (border_right, border_lower),
        ]

        points_ur = [
            (border_right, border_upper + caret_length),
            (border_right, border_upper),
            (border_right - caret_length, border_upper),
            (border_right, border_upper),
        ]

        points_ul = [
            (border_left, border_upper + caret_length),
            (border_left, border_upper),
            (border_left + caret_length, border_upper),
            (border_left, border_upper),
        ]

        points_ll = [
            (border_left, border_lower - caret_length),
            (border_left, border_lower),
            (border_left + caret_length, border_lower),
            (border_left, border_lower),
        ]

        point_list = [points_lr, points_ur, points_ul, points_ll]

        dc.DrawPolygonList(point_list, pens=pen, brushes=brush)

        self.old_cursor_row_col = row, col
1233108
private void paintCell(SeaGlassContext context, Graphics g, Rectangle cellRect, int row, int column) {
        if (table.isEditing() && table.getEditingRow() == row && table.getEditingColumn() == column) {
            Component component = table.getEditorComponent();

            component.setBounds(cellRect);
            component.validate();
        } else {
            TableCellRenderer renderer  = table.getCellRenderer(row, column);
            Component         component = table.prepareRenderer(renderer, row, column);

            rendererPane.paintComponent(g, component, table, cellRect.x, cellRect.y, cellRect.width, cellRect.height, true);
        }
    }
112258
function(){
		var cell = this.getcell();
		if(cell.isnull || cell===this.mouseCell){ return;}
		if(this.inputData===null){ this.inputData = (cell.ice()?0:6);}

		cell.setQues(this.inputData);
		cell.drawaround();
		this.mouseCell = cell;
	}
1137693
def draw(self):
        """"""

        # Content is only rendered within rect
        self.context.save()
        self.context.rectangle(*self.rect)
        self.context.clip()

        content = self.get_cell_content()

        pos_x, pos_y = self.rect[:2]
        self.context.translate(pos_x + 2, pos_y + 2)

        cell_attributes = self.code_array.cell_attributes

        # Do not draw cell content if cell is too small
        # This allows blending out small cells by reducing height to 0

        if self.rect[2] < cell_attributes[self.key]["borderwidth_right"] or \
           self.rect[3] < cell_attributes[self.key]["borderwidth_bottom"]:
            self.context.restore()
            return

        if self.code_array.cell_attributes[self.key]["button_cell"]:
            # Render a button instead of the cell
            label = self.code_array.cell_attributes[self.key]["button_cell"]
            self.draw_button(1, 1, self.rect[2]-5, self.rect[3]-5, label)

        elif isinstance(content, wx._gdi.Bitmap):
            # A bitmap is returned --> Draw it!
            self.draw_bitmap(content)

        elif pyplot is not None and isinstance(content, pyplot.Figure):
            # A matplotlib figure is returned --> Draw it!
            self.draw_matplotlib_figure(content)

        elif isinstance(content, basestring) and is_svg(content):
            # The content is a vaid SVG xml string
            self.draw_svg(content)

        elif content is not None:
            self.draw_text(content)

        self.context.translate(-pos_x - 2, -pos_y - 2)

        # Remove clipping to rect
        self.context.restore()
538754
function(){
		var cell = this.getcell();
		if(cell.isnull || cell===this.mouseCell){ return;}

		this.mouseCell = cell;

		var clist = new this.klass.CellList([cell]);
		if(this.puzzle.playmode){ clist.ansclear();}
		else                    { clist.allclear();}

		cell.draw();
	}
1190229
function Canvas(width, height) {
  var canvas = new NodeCanvas(width, height);
  var ctx = canvas.getContext('2d');
  this.canvas = canvas;
  this.ctx = ctx;
}
1032127
private void paintCells(SeaGlassContext context, Graphics g, int rMin, int rMax, int cMin, int cMax) {
        JTableHeader header        = table.getTableHeader();
        TableColumn  draggedColumn = (header == null) ? null : header.getDraggedColumn();

        TableColumnModel cm           = table.getColumnModel();
        int              columnMargin = cm.getColumnMargin();

        Rectangle   cellRect;
        TableColumn aColumn;
        int         columnWidth;

        if (table.getComponentOrientation().isLeftToRight()) {
            for (int row = rMin; row <= rMax; row++) {
                cellRect = table.getCellRect(row, cMin, false);
                for (int column = cMin; column <= cMax; column++) {
                    aColumn        = cm.getColumn(column);
                    columnWidth    = aColumn.getWidth();
                    cellRect.width = columnWidth - columnMargin;
                    if (aColumn != draggedColumn) {
                        paintCell(context, g, cellRect, row, column);
                    }

                    cellRect.x += columnWidth;
                }
            }
        } else {
            for (int row = rMin; row <= rMax; row++) {
                cellRect = table.getCellRect(row, cMin, false);
                aColumn  = cm.getColumn(cMin);
                if (aColumn != draggedColumn) {
                    columnWidth    = aColumn.getWidth();
                    cellRect.width = columnWidth - columnMargin;
                    paintCell(context, g, cellRect, row, cMin);
                }

                for (int column = cMin + 1; column <= cMax; column++) {
                    aColumn        =  cm.getColumn(column);
                    columnWidth    =  aColumn.getWidth();
                    cellRect.width =  columnWidth - columnMargin;
                    cellRect.x     -= columnWidth;
                    if (aColumn != draggedColumn) {
                        paintCell(context, g, cellRect, row, column);
                    }
                }
            }
        }

        // Paint the dragged column if we are dragging.
        if (draggedColumn != null) {
            paintDraggedArea(context, g, rMin, rMax, draggedColumn, header.getDraggedDistance());
        }

        // Remove any renderers that may be left in the rendererPane.
        rendererPane.removeAll();
    }
1009070
public void draw()
	{
		m_rootItem.updateColSpans();

		String nbRows = String.valueOf( m_rows.size() );
		int nbHeaders = m_rowHeaders.size();

		for( int i = 0; i < nbHeaders; i++ )
			m_rowHeaders.get( i ).m_td.setAttribute( "rowspan", nbRows );
	}

	public class RowHdrImpl
	{
		Element m_tr;
		Element m_td;

		public void setText( String text )
		{
			m_td.setInnerText( text );
		}
	}

	public RowHdrImpl addRowHeader()
	{
		RowHdrImpl item = new RowHdrImpl();
		m_rowHeaders.add( item );

		if( m_rows.isEmpty() )
		{
			Element tr = DOM.createTR();
			m_rows.add( tr );
			m_thead.appendChild( tr );
		}

		item.m_tr = m_rows.get( 0 );

		item.m_td = DOM.createTH();
		item.m_tr.appendChild( item.m_td );

		return item;
	}

	public class ItemImpl
	{
		int m_level = -2;
		int m_nbLeaves = -1;

		ItemImpl m_parent;
		ArrayList<ItemImpl> m_childs = new ArrayList<ItemImpl>();

		Element m_tr = null;
		Element m_td = null;

		ItemImpl( ItemImpl parent )
		{
			m_parent = parent;
			if( m_parent != null )
				m_parent.m_childs.add( this );
		}

		public void setText( String text )
		{
			m_td.setInnerText( text );
		}

		public void setWidget( Widget w )
		{
			setText( "" );
			add( w, m_td );
		}

		void updateColSpans()
		{
			for( ItemImpl c : m_childs )
			{
				int nbLeaf = c.getNbLeaves();
				c.m_td.setAttribute( "colspan", String.valueOf( nbLeaf ) );
				c.updateColSpans();
			}
		}

		int getNbLeaves()
		{
			if( m_nbLeaves == -1 )
			{
				if( m_childs.isEmpty() )
					m_nbLeaves = 1;
				else
				{
					int nb = 0;
					for( ItemImpl c : m_childs )
						nb += c.getNbLeaves();
					m_nbLeaves = nb;
				}
			}

			return m_nbLeaves;
		}

		int getLevel()
		{
			if( m_level == -2 )
			{
				if( m_parent == null )
					m_level = -1;
				else
					m_level = 1 + m_parent.getLevel();
			}

			return m_level;
		}

		ItemImpl getPreviousAtSameLevel()
		{
			return getPreviousAtLevel( getLevel() );
		}

		ItemImpl getLastDescendant( int level )
		{
			int myLevel = getLevel();
			if( level > myLevel )
				return null;
			if( myLevel == level )
				return this;

			int i = m_childs.size() - 1;
			while( i >= 0 )
			{
				ItemImpl t = getLastDescendant( level );
				if( t != null )
					return t;
				i--;
			}

			return null;
		}

		ItemImpl getPreviousAtLevel( int level )
		{
			if( m_parent == null )
				return null;

			ItemImpl position = this;
			ItemImpl ancestor = m_parent;
			while( ancestor != null )
			{
				int prevIdx = ancestor.m_childs.indexOf( position ) - 1;
				while( prevIdx >= 0 )
				{
					// test getLastDescendant( level )
					ItemImpl t = ancestor.m_childs.get( prevIdx ).getLastDescendant( level );
					if( t != null )
						return t;
					prevIdx--;
				}

				// did not find, so go to superior parent
				position = ancestor;
				ancestor = ancestor.m_parent;
			}

			// did not find, so return null
			return null;
		}
	}

	public ItemImpl addItem( ItemImpl parentItem )
	{
		ItemImpl item = new ItemImpl( parentItem == null ? m_rootItem : parentItem );
		int level = item.getLevel();

		while( m_rows.size() < level + 1 )
		{
			Element tr = DOM.createTR();
			m_thead.appendChild( tr );
			m_rows.add( tr );
		}

		item.m_tr = m_rows.get( level );

		// th is inserted after the last child of our parent
		item.m_td = DOM.createTH();
		ItemImpl previousItem = item.getPreviousAtSameLevel();
		if( previousItem != null )
			item.m_tr.insertAfter( item.m_td, previousItem.m_td );
		else
			item.m_tr.appendChild( item.m_td );

		return item;
	}
}