// get the characters we need to generate private static char[] getCharactersToGenerate(string inputText, int codePage, bool generateSpace) { CodePageInfo cpi = new CodePageInfo(codePage); // Expand and remove all ranges from the input text (look for << x - y >> // expand the ranges into the input text inputText = expandAndRemoveCharacterRanges(inputText, codePage); List <char> characterList = new List <char>(); List <char> CodePageCharacterList = new List <char>(cpi.GetAllValidCharacter()); // iterate over the characters in the textbox characterList = inputText.Aggregate <char, List <char> >(new List <char>(), (list, c) => { if (c == ' ' && !generateSpace) { } // skip - space is not encoded rather generated dynamically by the driver else if (c == '\n' || c == '\r' || c == '\t') { } // dont generate newlines or tab else { list.Add(c); } return(list); }); // remove dublicats and sort // remove all charaters not includet in codepage and return return(CodePageCharacterList .Intersect(characterList) .Distinct() .OrderBy(p => cpi.GetOffsetFromCharacter(p)) .ToArray()); }
// genereate a list of blocks describing the characters private List <CharacterDescriptor>[] generateCharacterDescriptorBlockList() { char currentCharacter, previousCharacter = '\0'; List <List <CharacterDescriptor> > characterBlockList = new List <List <CharacterDescriptor> >(); // initialize first block List <CharacterDescriptor> characterBlock = null; CodePageInfo cpi = new CodePageInfo(OutConfig.CodePage); // get the difference between two characters required to create a new group int differenceBetweenCharsForNewGroup = OutConfig.generateLookupBlocks ? OutConfig.lookupBlocksNewAfterCharCount : int.MaxValue; // iterate over characters, saving previous character each time for (int charIndex = 0; charIndex < Characters.Length; ++charIndex) { // get character currentCharacter = Characters[charIndex].Character; // check if this character is too far from the previous character and it isn't the first char if (cpi.GetCharacterDifferance(previousCharacter, currentCharacter) < differenceBetweenCharsForNewGroup && previousCharacter != '\0') { // it may not be far enough to generate a new group but it still may be non-sequential // in this case we need to generate place holders int previousCharacterOffset = cpi.GetOffsetFromCharacter(previousCharacter); int currentCharacterOffset = cpi.GetOffsetFromCharacter(currentCharacter); for (int sequentialCharIndex = previousCharacterOffset + 1; sequentialCharIndex < currentCharacterOffset; ++sequentialCharIndex) { // add the character placeholder to the current char block characterBlock.Add(new CharacterDescriptor(this)); } // fall through and add to current block } else { // done with current block, add to list (null is for first character which hasn't // created a group yet) if (characterBlock != null) { characterBlockList.Add(characterBlock); } // create new block characterBlock = new List <CharacterDescriptor>(); } // add to current block characterBlock.Add(Characters[charIndex]); // save previous char previousCharacter = currentCharacter; } // done; add current block to list characterBlockList.Add(characterBlock); return(characterBlockList.ToArray()); }
// populate the fields void populateControls() { // set datasources cbxPaddingHoriz.DataSource = Enum.GetNames(typeof(OutputConfiguration.PaddingRemoval)); cbxPaddingVert.DataSource = Enum.GetNames(typeof(OutputConfiguration.PaddingRemoval)); cbxCommentStyle.DataSource = Enum.GetNames(typeof(OutputConfiguration.CommentStyle)); cbxBitLayout.DataSource = Enum.GetNames(typeof(OutputConfiguration.BitLayout)); cbxByteFormat.DataSource = Enum.GetNames(typeof(OutputConfiguration.ByteFormat)); cbxRotation.DataSource = OutputConfiguration.Rotation.GetNames(); // display string arrays cbxCharWidthFormat.Items.AddRange(OutputConfiguration.DescriptorFormatDisplayString); cbxCharHeightFormat.Items.AddRange(OutputConfiguration.DescriptorFormatDisplayString); cbxFontHeightFormat.Items.AddRange(OutputConfiguration.DescriptorFormatDisplayString); cbxImgWidthFormat.Items.AddRange(OutputConfiguration.DescriptorFormatDisplayString); cbxImgHeightFormat.Items.AddRange(OutputConfiguration.DescriptorFormatDisplayString); cbxCharacterEncoding.Items.AddRange(CodePageInfo.GetEncoderNameList()); // add leading cbxByteLeadingChar.Items.Add(OutputConfiguration.ByteLeadingStringBinary); cbxByteLeadingChar.Items.Add(OutputConfiguration.ByteLeadingStringHex); txtBmpVisualizerChar.Items.AddRange(OutputConfiguration.CommentVisualizerChar); // re-populate dropdown m_outputConfigurationManager.comboBoxPopulate(cbxOutputConfigurations); }
// output configuration to form void loadFormToOutputConfiguration(ref OutputConfiguration outputConfig) { // load combo boxes outputConfig.paddingRemovalHorizontal = (OutputConfiguration.PaddingRemoval)Enum.Parse(typeof(OutputConfiguration.PaddingRemoval), cbxPaddingHoriz.Text); outputConfig.paddingRemovalVertical = (OutputConfiguration.PaddingRemoval)Enum.Parse(typeof(OutputConfiguration.PaddingRemoval), cbxPaddingVert.Text); int.TryParse(tbWidth.Text, out outputConfig.clippingHoriz); int.TryParse(tbHeight.Text, out outputConfig.clippingVert); outputConfig.commentStyle = (OutputConfiguration.CommentStyle)Enum.Parse(typeof(OutputConfiguration.CommentStyle), cbxCommentStyle.Text); outputConfig.bitLayout = (OutputConfiguration.BitLayout)Enum.Parse(typeof(OutputConfiguration.BitLayout), cbxBitLayout.Text); outputConfig.byteFormat = (OutputConfiguration.ByteFormat)Enum.Parse(typeof(OutputConfiguration.ByteFormat), cbxByteFormat.Text); outputConfig.rotation = OutputConfiguration.Rotation.Parse(cbxRotation.Text); outputConfig.descCharWidth = (OutputConfiguration.DescriptorFormat)Array.IndexOf(OutputConfiguration.DescriptorFormatDisplayString, cbxCharWidthFormat.Text); outputConfig.descCharHeight = (OutputConfiguration.DescriptorFormat)Array.IndexOf(OutputConfiguration.DescriptorFormatDisplayString, cbxCharHeightFormat.Text); outputConfig.descFontHeight = (OutputConfiguration.DescriptorFormat)Array.IndexOf(OutputConfiguration.DescriptorFormatDisplayString, cbxFontHeightFormat.Text); outputConfig.descImgWidth = (OutputConfiguration.DescriptorFormat)Array.IndexOf(OutputConfiguration.DescriptorFormatDisplayString, cbxImgWidthFormat.Text); outputConfig.descImgHeight = (OutputConfiguration.DescriptorFormat)Array.IndexOf(OutputConfiguration.DescriptorFormatDisplayString, cbxImgHeightFormat.Text); // text boxes outputConfig.byteLeadingString = cbxByteLeadingChar.Text; outputConfig.spaceGenerationPixels = int.Parse(txtSpacePixels.Text); outputConfig.lookupBlocksNewAfterCharCount = int.Parse(txtLookupBlocksNewAfterCharCount.Text); outputConfig.varNfBitmaps = txtVarNfFontBitmaps.Text; outputConfig.varNfCharInfo = txtVarNfCharInfo.Text; outputConfig.varNfFontInfo = txtVarNfFontInfo.Text; outputConfig.varNfImageBitmap = txtVarNfImageBitmap.Text; outputConfig.varNfImageInfo = txtVarNfImageInfo.Text; // load check boxes outputConfig.flipHorizontal = cbxFlipHoriz.Checked; outputConfig.flipVertical = cbxFlipVert.Checked; outputConfig.addCommentVariableName = cbxCommentVarName.Checked; outputConfig.addCommentCharVisualizer = cbxCommentCharVisual.Checked; outputConfig.addCommentCharDescriptor = cbxCommentCharDesc.Checked; outputConfig.generateSpaceCharacterBitmap = cbxGenerateSpaceBitmap.Checked; outputConfig.generateLookupArray = cbxGenerateLookupArray.Checked; outputConfig.byteOrderMsbFirst = cbxByteOrderMsbFirst.Checked; outputConfig.bmpVisualizerChar = (txtBmpVisualizerChar.Text.Length >= 1) ? txtBmpVisualizerChar.Text[0] : OutputConfiguration.CommentVisualizerCharDefault; outputConfig.bmpVisualizerCharEmpty = (txtBmpVisualizerChar.Text.Length >= 2) ? txtBmpVisualizerChar.Text[1] : OutputConfiguration.CommendVisualizerCharEmptyDefault; outputConfig.CodePage = CodePageInfo.GetCodepage(cbxCharacterEncoding.Text); outputConfig.addCodePage = cbxAddCodePage.Checked; outputConfig.generateLookupBlocks = cbxGenerateLookupBlocks.Checked; // radio buttons // -- wrap if (rbnLineWrapAtColumn.Checked) { outputConfig.lineWrap = OutputConfiguration.LineWrap.AtColumn; } else { outputConfig.lineWrap = OutputConfiguration.LineWrap.AtBitmap; } }
// output configuration to form void loadOutputConfigurationToForm(OutputConfiguration outputConfig) { // set flag m_loadingOutputConfigurationToForm = true; // load combo boxes cbxPaddingHoriz.SelectedIndex = (int)outputConfig.paddingRemovalHorizontal; cbxPaddingVert.SelectedIndex = (int)outputConfig.paddingRemovalVertical; cbxCommentStyle.SelectedIndex = (int)outputConfig.commentStyle; cbxBitLayout.SelectedIndex = (int)outputConfig.bitLayout; cbxByteOrderMsbFirst.Checked = outputConfig.byteOrderMsbFirst; cbxByteFormat.SelectedIndex = (int)outputConfig.byteFormat; cbxRotation.SelectedIndex = (int)outputConfig.rotation; cbxCharWidthFormat.SelectedIndex = (int)outputConfig.descCharWidth; cbxCharHeightFormat.SelectedIndex = (int)outputConfig.descCharHeight; cbxFontHeightFormat.SelectedIndex = (int)outputConfig.descFontHeight; cbxImgWidthFormat.SelectedIndex = (int)outputConfig.descImgWidth; cbxImgHeightFormat.SelectedIndex = (int)outputConfig.descImgHeight; // text boxes cbxByteLeadingChar.Text = outputConfig.byteLeadingString; txtSpacePixels.Text = outputConfig.spaceGenerationPixels.ToString(); txtLookupBlocksNewAfterCharCount.Text = outputConfig.lookupBlocksNewAfterCharCount.ToString(); cbxOutputConfigurations.Text = outputConfig.displayName; txtVarNfFontBitmaps.Text = outputConfig.varNfBitmaps; txtVarNfCharInfo.Text = outputConfig.varNfCharInfo; txtVarNfFontInfo.Text = outputConfig.varNfFontInfo; txtVarNfImageBitmap.Text = outputConfig.varNfImageBitmap; txtVarNfImageInfo.Text = outputConfig.varNfImageInfo; // load check boxes cbxFlipHoriz.Checked = outputConfig.flipHorizontal; cbxFlipVert.Checked = outputConfig.flipVertical; cbxCommentVarName.Checked = outputConfig.addCommentVariableName; cbxCommentCharVisual.Checked = outputConfig.addCommentCharVisualizer; cbxCommentCharDesc.Checked = outputConfig.addCommentCharDescriptor; cbxGenerateSpaceBitmap.Checked = outputConfig.generateSpaceCharacterBitmap; cbxGenerateLookupArray.Checked = outputConfig.generateLookupArray; txtBmpVisualizerChar.Text = "" + outputConfig.bmpVisualizerChar + outputConfig.bmpVisualizerCharEmpty; cbxGenerateLookupBlocks.Checked = outputConfig.generateLookupBlocks; cbxCharacterEncoding.Text = CodePageInfo.GetCodepageName(outputConfig.CodePage); cbxAddCodePage.Checked = outputConfig.addCodePage; // radio buttons // -- wrap rbnLineWrapAtColumn.Checked = (outputConfig.lineWrap == OutputConfiguration.LineWrap.AtColumn); rbnLineWrapAtBitmap.Checked = !rbnLineWrapAtColumn.Checked; // clear flag m_loadingOutputConfigurationToForm = false; }
// get font info from string private void populateFontInfoFromCharacters() { // do nothing if no chars defined if (Characters.Length == 0) { return; } // total offset int charByteOffset = 0; // set start char FirstChar = CodePageInfo.GetLastValidCharacter(); LastChar = CodePageInfo.GetFirstValidCharacter(); // the fixed absolute character height this.FixedAbsolutCharHeight = OutConfig.rotation.getAbsoluteCharacterDimensions(Characters[0].BitmapToGenerate.Size).Height; // iterate through letter string for (int charIdx = 0; charIdx < Characters.Length; ++charIdx) { // skip empty bitmaps if (Characters[charIdx].BitmapToGenerate == null) { continue; } // get char char currentChar = Characters[charIdx].Character; // is this character smaller than start char? if (CodePageInfo.GetCharacterDifferance(currentChar, FirstChar) > 0) { FirstChar = currentChar; } // is this character bigger than end char? if (CodePageInfo.GetCharacterDifferance(currentChar, LastChar) < 0) { LastChar = currentChar; } // populate offset of character Characters[charIdx].OffsetInBytes = charByteOffset; // increment byte offset charByteOffset += Characters[charIdx].DataLength; } }
// expand and remove character ranges ( look for << x - y >> ) private static string expandAndRemoveCharacterRanges(string s, int codePage) { // create the search pattern //String searchPattern = @"<<.*-.*>>"; String searchPattern = @"<<(?<rangeStart>.*?)-(?<rangeEnd>.*?)>>"; // create the regex Regex regex = new Regex(searchPattern, RegexOptions.Multiline); // get matches MatchCollection regexMatches = regex.Matches(s.Replace(" ", "")); // holds the number of characters removed int charactersRemoved = 0; CodePageInfo cp = new CodePageInfo(codePage); // for each match foreach (Match regexMatch in regexMatches) { // get range start and end int rangeStart = 0, rangeEnd = 0; // try to parse ranges if (TryParseCharacterRangePoint(regexMatch.Groups["rangeStart"].Value, out rangeStart) && TryParseCharacterRangePoint(regexMatch.Groups["rangeEnd"].Value, out rangeEnd)) { // remove this from the string s = s.Remove(regexMatch.Index - charactersRemoved, regexMatch.Length); // save the number of chars removed so that we can fixup index (the index // of the match changes as we remove characters) charactersRemoved += regexMatch.Length; // create a string from these values for (int charIndex = rangeStart; charIndex <= rangeEnd; ++charIndex) { // shove this character to a encodet char container char unicodeChar = cp.GetCharacterFromOffset(charIndex); // add this to the string s += unicodeChar; } } } return(s); }
// populate preformatted text private void populateTextInsertCheckbox() { string allEnglish = "", numbers = "", letters = "", uppercaseLetters = "", lowercaseLetters = "", symbols = ""; // generate characters for (char character = ' '; character < 127; ++character) { // add to all allEnglish += character; // classify letter if (Char.IsNumber(character)) { numbers += character; } else if (Char.IsSymbol(character)) { symbols += character; } else if (Char.IsLetter(character) && Char.IsLower(character)) { letters += character; lowercaseLetters += character; } else if (Char.IsLetter(character) && !Char.IsLower(character)) { letters += character; uppercaseLetters += character; } } string allEuropean = allEnglish, extraPunctuations = "", extraSymbols = "", extraNumbers = ""; for (char character = (char)129; character <= 255; ++character) { if (Char.IsLetter(character)) { allEuropean += character; } if (Char.IsPunctuation(character)) { extraPunctuations += character; } if (Char.IsSymbol(character)) { extraSymbols += character; } if (Char.IsNumber(character)) { extraNumbers += character; } } // add items cbxTextInsert.Items.Add(new ComboBoxItem("All European", allEuropean)); cbxTextInsert.Items.Add(new ComboBoxItem("All English(ASCCI)", allEnglish)); cbxTextInsert.Items.Add(new ComboBoxItem("Numbers (0-9)", numbers)); cbxTextInsert.Items.Add(new ComboBoxItem("Letters (A-z)", letters)); cbxTextInsert.Items.Add(new ComboBoxItem("Lowercase letters (a-z)", lowercaseLetters)); cbxTextInsert.Items.Add(new ComboBoxItem("Uppercase letters (A-Z)", uppercaseLetters)); cbxTextInsert.Items.Add(new ComboBoxItem("Extra Punctuations", extraPunctuations)); cbxTextInsert.Items.Add(new ComboBoxItem("Extra Symbols", extraSymbols)); cbxTextInsert.Items.Add(new ComboBoxItem("Extra Numbers", extraNumbers)); foreach (string s in CodePageInfo.GetEncoderNameList()) { if (s.ToLower() != "us-ascii" //&& s.ToLower() != "utf-16" ) { cbxTextInsert.Items.Add(new ComboBoxItem(s, new string(new CodePageInfo(s).GetAllValidCharacter()))); } } // select the first cbxTextInsert.SelectedIndex = 0; }
// get the display string for a character private static string getCharacterDisplayString(CodePageInfo codePage, char character) { // return string return(codePage.GetOffsetFromCharacter(character).ToString()); }
public FontDescriptor(OutputConfiguration config, char[] characters, Font font) { Font = font; OutConfig = config; CodePageInfo = new CodePageInfo(config.CodePage); // // init char infos // Characters = characters.Select(c => new CharacterDescriptor(this, c)).ToArray(); // // Find the widest bitmap size we are going to draw // Size largestBitmap = Characters.Aggregate(new Size(), (size, chi) => { return(new Size( chi.SizeCharacter.Width > size.Width ? chi.SizeCharacter.Width : size.Width, chi.SizeCharacter.Height > size.Height ? chi.SizeCharacter.Height : size.Height)); }); // // create bitmaps per characater // Characters.ToList().ForEach(c => c.GenerateOriginal(largestBitmap)); // // iterate through all bitmaps and find the tightest common border. only perform // this if the configuration specifies // // this will contain the values of the tightest border around the characters Border tightestCommonBorder = Border.Empty; // only perform if padding type specifies if (OutConfig.paddingRemovalHorizontal == OutputConfiguration.PaddingRemoval.Fixed || OutConfig.paddingRemovalVertical == OutputConfiguration.PaddingRemoval.Fixed || OutConfig.paddingRemovalHorizontal == OutputConfiguration.PaddingRemoval.Clipped || OutConfig.paddingRemovalVertical == OutputConfiguration.PaddingRemoval.Clipped) { // find the common tightest border tightestCommonBorder = Characters.ToList(). Select <CharacterDescriptor, Border>(c => c.OriginalBorder) .Aggregate <Border, Border>(Border.Empty, (p1, p2) => new Border( p1.Left <p2.Left?p1.Left : p2.Left, p1.Top <p2.Top?p1.Top : p2.Top, p1.Right> p2.Right?p1.Right : p2.Right, p1.Bottom> p2.Bottom ? p1.Bottom : p2.Bottom) ); } // // iterate thruogh all bitmaps and generate the bitmap we will convert to string // this means performing all manipulation (pad remove, flip) // // iterate over characters Characters.ToList().ForEach(c => { // check if bitmap exists if (c.GenerateManipulatetBitmap(tightestCommonBorder)) { // create the page array for the character c.GeneratePageArray(); } }); // populate font info populateFontInfoFromCharacters(); GenerateStringsFromFontInfo(); }
// generate the strings private void GenerateStringsFromFontInfo() { StringBuilder sourceText = new StringBuilder(); StringBuilder headerText = new StringBuilder(); if (OutConfig.addCommentVariableName) { // add source file header sourceText.AppendFormat("{0}" + OutConfig.nl + "{1} Font data for {2}" + OutConfig.nl + "{3}" + OutConfig.nl + OutConfig.nl, OutConfig.CommentStart, OutConfig.CommentBlockMiddle, getFontName(Font, false), OutConfig.CommentBlockEnd); // add source header sourceText.AppendFormat("{0}Character bitmaps for {1} {2}" + OutConfig.nl, OutConfig.CommentStart, getFontName(Font, false), OutConfig.CommentEnd); // add header file header headerText.AppendFormat("{0}Font data for {1} {2}" + OutConfig.nl, OutConfig.CommentStart, getFontName(Font, false), OutConfig.CommentEnd); } // get bitmap name string charBitmapVarName = String.Format(OutConfig.varNfBitmaps, getFontName(Font, true)) + "[]"; // source var sourceText.AppendFormat("{0} = " + OutConfig.nl + "{{" + OutConfig.nl, charBitmapVarName); Characters.ToList().ForEach(chi => chi.GenerateCharacterDataDescriptorAndVisulazer()); Characters.Aggregate(sourceText, (sb, chi) => { // skip empty bitmaps if (chi.BitmapToGenerate == null) { return(sb); } // now add letter array sourceText.Append(chi.Descriptor); // space out if (OutConfig.addCommentCharDescriptor && chi.Character != chi.ParentFontInfo.LastChar) { // space between chars sb.Append(OutConfig.nl); } return(sb); }); // space out sourceText.Append("};" + OutConfig.nl + OutConfig.nl); // // Charater descriptor // // whether or not block lookup was generated bool blockLookupGenerated = false; // check if required by configuration if (OutConfig.generateLookupArray) { // generate the lookup array blockLookupGenerated = generateStringsFromCharacterDescriptorBlockList(sourceText, headerText); } // // Font descriptor // // according to config if (OutConfig.addCommentVariableName) { // result string sourceText.AppendFormat("{0}Font information for {1} {2}" + OutConfig.nl, OutConfig.CommentStart, getFontName(Font, false), OutConfig.CommentEnd); } // character name string fontInfoVarName = String.Format(OutConfig.varNfFontInfo, getFontName(Font, true)); // add character array for header headerText.AppendFormat("extern {0};" + OutConfig.nl, fontInfoVarName); // the font character height string fontCharHeightString = ""; // get character height sstring - displayed according to output configuration if (OutConfig.descFontHeight != OutputConfiguration.DescriptorFormat.DontDisplay) { // convert the value fontCharHeightString = String.Format("\t{0}, {1} Character height{2}" + OutConfig.nl, MyExtensions.ConvertValueByDescriptorFormat(OutConfig.descFontHeight, FixedAbsolutCharHeight), OutConfig.CommentStart, OutConfig.CommentEnd); } string fontCodePage = ""; if (OutConfig.addCodePage) { fontCodePage = string.Format("\t{0}, {1} CodePage {3}{2}" + OutConfig.nl, OutConfig.CodePage, OutConfig.CommentStart, OutConfig.CommentEnd, CodePageInfo.GetCodepageName(OutConfig.CodePage)); } string spaceCharacterPixelWidthString = ""; // get space char width, if it is up to driver to generate if (!OutConfig.generateSpaceCharacterBitmap) { // convert the value spaceCharacterPixelWidthString = String.Format("\t{0}, {1} Width, in pixels, of space character{2}" + OutConfig.nl, OutConfig.spaceGenerationPixels, OutConfig.CommentStart, OutConfig.CommentEnd); } // font info sourceText.AppendFormat("{2} =" + OutConfig.nl + "{{" + OutConfig.nl + "{3}" + "\t{4}, {0} First character '{9}'{1}" + OutConfig.nl + "\t{5}, {0} Last character '{10}'{1}" + OutConfig.nl + "{6}" + "{7}" + "\t{8}, {0} Character bitmap array{1}" + OutConfig.nl + "{11}" + "}};" + OutConfig.nl, OutConfig.CommentStart, OutConfig.CommentEnd, fontInfoVarName, fontCharHeightString, getCharacterDisplayString(CodePageInfo, FirstChar), getCharacterDisplayString(CodePageInfo, LastChar), spaceCharacterPixelWidthString, getFontInfoDescriptorsString(blockLookupGenerated, OutConfig, Font), MyExtensions.GetVariableNameFromExpression(String.Format(OutConfig.varNfBitmaps, getFontName(Font, true))), FirstChar, LastChar, fontCodePage); // add the appropriate entity to the header if (blockLookupGenerated) { // add block lookup to header headerText.AppendFormat("extern const FONT_CHAR_INFO_LOOKUP {0}[];" + OutConfig.nl, getCharacterDescriptorArrayLookupDisplayString(Font)); } else { // add block lookup to header headerText.AppendFormat("extern {0}[];" + OutConfig.nl, String.Format(OutConfig.varNfCharInfo, getFontName(Font, true))); } TextSource = sourceText.ToString(); TextHeader = headerText.ToString(); }