code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* Copyright 2012 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using Google.Apis.Dfareporting.v1_2; using Google.Apis.Dfareporting.v1_2.Data; using Google.Apis.Samples.Helper; namespace DfaReporting.Sample { /// <summary> /// This example gets all reports available to the given user profile. /// </summary> internal class GetAllReportsHelper { private readonly DfareportingService service; /// <summary> /// Instantiate a helper for listing all reports available. /// </summary> /// <param name="service">DfaReporting service object used to run the requests.</param> public GetAllReportsHelper(DfareportingService service) { this.service = service; } /// <summary> /// Lists all available reports for the given user profile. /// </summary> /// <param name="userProfileId">The ID number of the DFA user profile to run this request as.</param> /// <param name="maxPageSize">The maximum number of results per page.</param> public void List(string userProfileId, int maxPageSize) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Listing all reports"); CommandLine.WriteLine("================================================================="); // Retrieve account list in pages and display data as we receive it. string pageToken = null; ReportList reports = null; do { var request = service.Reports.List(userProfileId); request.MaxResults = maxPageSize; request.PageToken = pageToken; reports = request.Execute(); foreach (var report in reports.Items) { CommandLine.WriteLine("Report with ID \"{0}\" and display name \"{1}\" was found.%n", report.Id, report.Name); } pageToken = reports.NextPageToken; } while (reports.Items.Count > 0); CommandLine.WriteLine(); } } }
zzfocuzz-deepbotcopy
DfaReporting.Sample/GetAllReportsHelper.cs
C#
asf20
2,765
/* Copyright 2012 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System.IO; using System.Net; using Google.Apis.Dfareporting.v1_2; using Google.Apis.Dfareporting.v1_2.Data; using File = Google.Apis.Dfareporting.v1_2.Data.File; using Google.Apis.Samples.Helper; namespace DfaReporting.Sample { /// <summary> /// This example downloads the contents of a report file. /// </summary> internal class DownloadReportFileHelper { private readonly DfareportingService service; /// <summary> /// Instantiate a helper for downloading the contents of report files. /// </summary> /// <param name="service">DfaReporting service object used to run the requests.</param> public DownloadReportFileHelper(DfareportingService service) { this.service = service; } /// <summary> /// Fetches the contents of a report file. /// </summary> /// <param name="reportFile">The completed report file to download.</param> public void Run(File reportFile) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Retrieving and printing a report file for report with ID {0}", reportFile.ReportId); CommandLine.WriteLine("The ID number of this report file is {0}", reportFile.Id); CommandLine.WriteLine("================================================================="); string url = reportFile.Urls.ApiUrl; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); service.Authenticator.ApplyAuthenticationToRequest(webRequest); using (Stream stream = webRequest.GetResponse().GetResponseStream()) { StreamReader reader = new StreamReader(new BufferedStream(stream)); string report = reader.ReadToEnd(); CommandLine.WriteLine(report); } } } }
zzfocuzz-deepbotcopy
DfaReporting.Sample/DownloadReportFileHelper.cs
C#
asf20
2,530
/* Copyright 2012 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using Google.Apis.Dfareporting.v1_2; using Google.Apis.Dfareporting.v1_2.Data; using Google.Apis.Samples.Helper; namespace DfaReporting.Sample { /// <summary> /// This example gets the first page of a particular type of dimension available for reporting in /// the given date range. You can use a similar workflow to retrieve the values for any dimension. /// /// The available dimension value names can be found here: /// https://developers.google.com/doubleclick-advertisers/reporting/v1.1/dimensions /// </summary> internal class GetDimensionValuesHelper { private readonly DfareportingService service; /// <summary> /// Instantiate a helper for retrieving dimension values. /// </summary> /// <param name="service">DfaReporting service object used to run the requests.</param> public GetDimensionValuesHelper(DfareportingService service) { this.service = service; } /// <summary> /// Lists the first page of results for a dimension value. /// </summary> /// <param name="dimensionName">The name of the dimension to retrieve values for.</param> /// <param name="userProfileId">The ID number of the DFA user profile to run this request as.</param> /// <param name="startDate">Values which existed after this start date will be returned.</param> /// <param name="endDate">Values which existed before this end date will be returned.</param> /// <param name="maxPageSize">The maximum page size to retrieve.</param> /// <returns>The first page of dimension values received.</returns> public DimensionValueList Query(string dimensionName, string userProfileId, DateTime startDate, DateTime endDate, int maxPageSize) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Listing available {0} values", dimensionName); CommandLine.WriteLine("================================================================="); // Create a dimension value query which selects available dimension values. var request = new DimensionValueRequest(); request.DimensionName = dimensionName; request.StartDate = DfaReportingDateConverterUtil.convert(startDate); request.EndDate = DfaReportingDateConverterUtil.convert(endDate); var dimensionQuery = service.DimensionValues.Query(request, userProfileId); dimensionQuery.MaxResults = maxPageSize; // Retrieve values and display them. var values = dimensionQuery.Execute(); if (values.Items.Count > 0) { foreach (var dimensionValue in values.Items) { CommandLine.WriteLine("{0} with value \"{1}\" was found.", dimensionName, dimensionValue.Value); } } else { CommandLine.WriteLine("No values found."); } CommandLine.WriteLine(); return values; } } }
zzfocuzz-deepbotcopy
DfaReporting.Sample/GetDimensionValuesHelper.cs
C#
asf20
3,875
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DfaReporting.Sample")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google")] [assembly: AssemblyProduct("DfaReporting.Sample")] [assembly: AssemblyCopyright("Copyright © Google Inc 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("05d799ca-03b7-4414-98f5-d066850a0877")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-deepbotcopy
DfaReporting.Sample/Properties/AssemblyInfo.cs
C#
asf20
1,427
/* Copyright 2012 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using Google.Apis.Dfareporting.v1_2; using Google.Apis.Dfareporting.v1_2.Data; using Google.Apis.Samples.Helper; namespace DfaReporting.Sample { /// <summary> /// This example creates a simple standard report for the given advertiser. /// </summary> internal class CreateStandardReportHelper { private readonly DfareportingService service; /// <summary> /// Instantiate a helper for creating standard reports. /// </summary> /// <param name="service">DfaReporting service object used to run the requests.</param> public CreateStandardReportHelper(DfareportingService service) { this.service = service; } /// <summary> /// Inserts (creates) a simple standard report for a given advertiser. /// </summary> /// <param name="userProfileId">The ID number of the DFA user profile to run this request as.</param> /// <param name="advertiser">The advertiser who the report is about.</param> /// <param name="startDate">The starting date of the report.</param> /// <param name="endDate">The ending date of the report.</param> /// <returns>The newly created report</returns> public Report Insert(string userProfileId, DimensionValue advertiser, DateTime startDate, DateTime endDate) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Creating a new standard report for advertiser {0}%n", advertiser.Value); CommandLine.WriteLine("================================================================="); // Create a report. var report = new Report(); report.Name = string.Format("API Report: Advertiser {0}", advertiser.Value); report.FileName = "api_report_files"; // Set the type of report you want to create. Available report types can be found in the description of // the type property: https://developers.google.com/doubleclick-advertisers/reporting/v1.1/reports report.Type = "FLOODLIGHT"; report.Type = "STANDARD"; // Create criteria. var criteria = new Report.CriteriaData(); criteria.DateRange = new DateRange { StartDate = DfaReportingDateConverterUtil.convert(startDate), EndDate = DfaReportingDateConverterUtil.convert(endDate) }; // Set the dimensions, metrics, and filters you want in the report. The available values can be found // here: https://developers.google.com/doubleclick-advertisers/reporting/v1.1/dimensions criteria.Dimensions = new List<SortedDimension> { new SortedDimension { Name = "dfa:advertiser" } }; criteria.MetricNames = new List<string> { "dfa:clicks", "dfa:impressions" }; criteria.DimensionFilters = new List<DimensionValue> { advertiser }; report.Criteria = criteria; Report result = service.Reports.Insert(report, userProfileId).Execute(); CommandLine.WriteLine("Created report with ID \"{0}\" and display name \"{1}\"", result.Id, result.Name); CommandLine.WriteLine(); return result; } } }
zzfocuzz-deepbotcopy
DfaReporting.Sample/CreateStandardReportHelper.cs
C#
asf20
4,068
/* Copyright 2012 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using Google.Apis.Dfareporting.v1_2; using Google.Apis.Dfareporting.v1_2.Data; using Google.Apis.Samples.Helper; namespace DfaReporting.Sample { /// <summary> /// This example creates a simple Floodlight report for the given Floodlight Configuration ID. /// </summary> internal class CreateFloodlightReportHelper { private readonly DfareportingService service; /// <summary> /// Instantiate a helper for creating floodlight reports. /// </summary> /// <param name="service">DfaReporting service object used to run the requests.</param> public CreateFloodlightReportHelper(DfareportingService service) { this.service = service; } /// <summary> /// Inserts (creates) a simple Floodlight report for a given Floodlight Configuration ID. /// </summary> /// <param name="userProfileId">The ID number of the DFA user profile to run this request as.</param> /// <param name="floodlightConfigId">The Floodlight configuration ID the report is about.</param> /// <param name="startDate">The starting date of the report.</param> /// <param name="endDate">The ending date of the report.</param> /// <returns>The newly created report</returns> public Report Insert(string userProfileId, DimensionValue floodlightConfigId, DateTime startDate, DateTime endDate) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Creating a new floodlight report for Floodlight config ID {0}", floodlightConfigId.Value); CommandLine.WriteLine("================================================================="); // Create a report. Report report = new Report(); report.Name = string.Format("API Floodlight Report: Floodlight ID {0}", floodlightConfigId.Value); report.FileName = "api_floodlight_report_files"; // Set the type of report you want to create. Available report types can be found in the description of // the type property: https://developers.google.com/doubleclick-advertisers/reporting/v1.1/reports report.Type = "FLOODLIGHT"; // Create criteria. var criteria = new Report.FloodlightCriteriaData(); criteria.DateRange = new DateRange { StartDate = DfaReportingDateConverterUtil.convert(startDate), EndDate = DfaReportingDateConverterUtil.convert(endDate) }; // Set the dimensions, metrics, and filters you want in the report. The available values can be found // here: https://developers.google.com/doubleclick-advertisers/reporting/v1.1/dimensions criteria.Dimensions = new List<SortedDimension> { new SortedDimension { Name = "dfa:floodlightConfigId" }, new SortedDimension { Name = "dfa:activity" }, new SortedDimension { Name = "dfa:advertiser" } }; criteria.MetricNames = new List<string> { "dfa:activityClickThroughConversions", "dfa:activityClickThroughRevenue", "dfa:activityViewThroughConversions", "dfa:activityViewThroughRevenue" }; criteria.DimensionFilters = new List<DimensionValue> { floodlightConfigId }; report.FloodlightCriteria = criteria; Report result = service.Reports.Insert(report, userProfileId).Execute(); CommandLine.WriteLine("Created report with ID \"{0}\" and display name \"{1}\"", result.Id, result.Name); CommandLine.WriteLine(); return result; } } }
zzfocuzz-deepbotcopy
DfaReporting.Sample/CreateFloodlightReportHelper.cs
C#
asf20
4,499
/* Copyright 2012 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; namespace DfaReporting.Sample { /// <summary> /// This simple utility converts <c>DateTime</c> objects to the <c>string</c> format that the DFA Reporting API /// always expects dates to be in. /// </summary> internal static class DfaReportingDateConverterUtil { private const string DateFormat = "yyyy-MM-dd"; /// <summary> /// Takes a <c>DateTime</c> object and converts it to the proper <c>string</c> format for the /// Dfa Reporting API. /// </summary> /// <param name="date">The date to be converted.</param> /// <returns>The given date in the proper format.</returns> public static string convert(DateTime date) { return date.ToString(DateFormat); } } }
zzfocuzz-deepbotcopy
DfaReporting.Sample/DfaReportingDateConverterUtil.cs
C#
asf20
1,357
<html> <title>Google .NET Client API &ndash; DfaReporting.Sample</title> <body> <h2>Instructions for the Google .NET Client API &ndash; DfaReporting.Sample</h2> <h3>Browse Online</h3> <ul> <li> <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FDfaReporting.Sample"> Browse Source </a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/DfaReporting.Sample/Program.cs?repo=samples"> Program.cs </a> </li> </ul> <h3>1. Checkout Instructions</h3> <p> <b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>. </p> <pre><code>cd <i>[someDirectory]</i></code></pre> <pre><code>hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p> <b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li> <a href="http://code.google.com/apis/console-help/#creatingdeletingprojects"> Create a project in Google APIs console </a> </li> <li> <a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the DFA Reporting API for your project </li> </ul> </p> <h3>Set up Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>DfaReporting.Sample\bin\Debug</i></li> <li> When prompted insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane. </li> </ul> </body> </html>
zzfocuzz-deepbotcopy
DfaReporting.Sample/README.html
HTML
asf20
1,971
/* Copyright 2012 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Threading; using Google.Apis.Dfareporting.v1_2; using Google.Apis.Dfareporting.v1_2.Data; using Google.Apis.Samples.Helper; using Google.Apis.Util; namespace DfaReporting.Sample { /// <summary> /// This example generates a report file from a report. /// </summary> internal class GenerateReportFileHelper { private readonly DfareportingService service; /// <summary> /// Instantiate a helper for generating a new file for a report. /// </summary> /// <param name="service">DfaReporting service object used to run the requests.</param> public GenerateReportFileHelper(DfareportingService service) { this.service = service; } /// <summary> /// Requests the generation of a new report file from a given report. /// </summary> /// <param name="userProfileId">The ID number of the DFA user profile to run this request as.</param> /// <param name="report">The report to request a new file for.</param> /// <returns>The generated report file.</returns> public File Run(string userProfileId, Report report, bool isSynchronous) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Generating a report file for report with ID {0}", report.Id); CommandLine.WriteLine("================================================================="); ReportsResource.RunRequest request = service.Reports.Run(userProfileId, report.Id); request.Synchronous = isSynchronous; File reportFile = request.Execute(); CommandLine.WriteLine("Report execution initiated. Checking for completion..."); reportFile = waitForReportRunCompletion(service, userProfileId, reportFile); if (!reportFile.Status.Equals("REPORT_AVAILABLE")) { CommandLine.WriteLine("Report file generation failed to finish. Final status is: {0}", reportFile.Status); return null; } CommandLine.WriteLine("Report file with ID \"{0}\" generated.", reportFile.Id); CommandLine.WriteLine(); return reportFile; } /// <summary> /// Waits for a report file to generate by polling for its status using exponential backoff. In the worst case, /// there will be 10 attempts to determine if the report is no longer processing. /// </summary> /// <param name="service">DfaReporting service object used to run the requests.</param> /// <param name="userProfileId">The ID number of the DFA user profile to run this request as.</param> /// <param name="file">The report file to poll the status of.</param> /// <returns>The report file object, either once it is no longer processing or /// once too much time has passed.</returns> private static File waitForReportRunCompletion(DfareportingService service, string userProfileId, File file) { ExponentialBackOff backOff = new ExponentialBackOff(); TimeSpan interval; file = service.Reports.Files.Get(userProfileId, file.ReportId, file.Id).Execute(); for (int i = 1; i <= backOff.MaxNumOfRetries; i++) { if (!file.Status.Equals("PROCESSING")) { break; } interval = backOff.GetNextBackOff(i); CommandLine.WriteLine("Polling again in {0} seconds.", interval); Thread.Sleep(interval); file = service.Reports.Files.Get(userProfileId, file.ReportId, file.Id).Execute(); } return file; } } }
zzfocuzz-deepbotcopy
DfaReporting.Sample/GenerateReportFileHelper.cs
C#
asf20
4,551
/* Copyright 2012 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using DotNetOpenAuth.OAuth2; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Dfareporting.v1_2; using Google.Apis.Dfareporting.v1_2.Data; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Util; namespace DfaReporting.Sample { /// <summary> /// A sample application that runs multiple requests against the DFA Reporting API. These include: /// <list type="bullet"> /// <item> /// <description>Listing all DFA user profiles for a user</description> /// </item> /// <item> /// <description>Listing the first 50 available advertisers for a user profile</description> /// </item> /// <item> /// <description>Creating a new standard report</description> /// </item> /// <item> /// <description>Listing the first 50 available Floodlight configuration IDs for a user profile</description> /// </item> /// <item> /// <description>Creating a new shared Floodlight report</description> /// </item> /// <item> /// <description>Generating a new report file from a report</description> /// </item> /// <item> /// <description>Downloading the contents of a report file</description> /// </item> /// <item> /// <description>Listing all available reports</description> /// </item> /// </list> /// </summary> internal class Program { private static readonly string DfaReportingScope = DfareportingService.Scopes.Dfareporting.GetStringValue(); private const string DevStorageScopeReadOnly = "https://www.googleapis.com/auth/devstorage.read_only"; private const int MaxListPageSize = 50; private const int MaxReportPageSize = 10; private static readonly DateTime StartDate = DateTime.Today.AddDays(-7); private static readonly DateTime EndDate = DateTime.Today; [STAThread] static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("DFA Reporting API Command Line Sample"); // Register the authenticator. FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials(); var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description) { ClientIdentifier = credentials.ClientId, ClientSecret = credentials.ClientSecret }; var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication); // Create the service. var service = new DfareportingService(new BaseClientService.Initializer { Authenticator = auth, ApplicationName = "DFA API Sample", }); // Choose a user profile ID to use in the following samples. string userProfileId = GetUserProfileId(service); // Create and run a standard report. CreateAndRunStandardReport(service, userProfileId); // Create and run a Floodlight report. CreateAndRunFloodlightReport(service, userProfileId); // List all of the Reports you have access to. new GetAllReportsHelper(service).List(userProfileId, MaxReportPageSize); CommandLine.PressAnyKeyToExit(); } private static string GetUserProfileId(DfareportingService service) { UserProfileList userProfiles = new GetAllUserProfilesHelper(service).Run(); if (userProfiles.Items.Count == 0) { CommandLine.WriteLine("No user profiles found."); CommandLine.PressAnyKeyToExit(); Environment.Exit(1); } return userProfiles.Items[0].ProfileId; } private static void CreateAndRunStandardReport(DfareportingService service, string userProfileId) { DimensionValueList advertisers = new GetDimensionValuesHelper(service).Query( "dfa:advertiser", userProfileId, StartDate, EndDate, MaxListPageSize); if (advertisers.Items.Count > 0) { // Get an advertiser to report on. DimensionValue advertiser = advertisers.Items[0]; Report standardReport = new CreateStandardReportHelper(service).Insert( userProfileId, advertiser, StartDate, EndDate); File file = new GenerateReportFileHelper(service).Run(userProfileId, standardReport, true); if (file != null) { // If the report file generation did not fail, display results. new DownloadReportFileHelper(service).Run(file); } } } private static void CreateAndRunFloodlightReport(DfareportingService service, string userProfileId) { DimensionValueList floodlightConfigIds = new GetDimensionValuesHelper(service).Query( "dfa:floodlightConfigId", userProfileId, StartDate, EndDate, MaxListPageSize); if (floodlightConfigIds.Items.Count > 0) { // Get a Floodlight Config ID, so we can run the rest of the samples. DimensionValue floodlightConfigId = floodlightConfigIds.Items[0]; Report floodlightReport = new CreateFloodlightReportHelper(service).Insert( userProfileId, floodlightConfigId, StartDate, EndDate); File file = new GenerateReportFileHelper(service).Run(userProfileId, floodlightReport, false); if (file != null) { // If the report file generation did not fail, display results. new DownloadReportFileHelper(service).Run(file); } } } private static IAuthorizationState GetAuthentication(NativeApplicationClient client) { // You should use a more secure way of storing the key here as // .NET applications can be disassembled using a reflection tool. const string STORAGE = "google.samples.dotnet.dfareporting"; const string KEY = "GV^F*(#$:P_NLOn890HC"; // Check if there is a cached refresh token available. IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY); if (state != null) { try { client.RefreshToken(state); return state; // Yes - we are done. } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { CommandLine.WriteError("Using existing refresh token failed: " + ex.Message); } } // Retrieve the authorization from the user. state = AuthorizationMgr.RequestNativeAuthorization(client, DfaReportingScope, DevStorageScopeReadOnly); AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state); return state; } } }
zzfocuzz-deepbotcopy
DfaReporting.Sample/Program.cs
C#
asf20
8,074
/* Copyright 2012 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using Google.Apis.Dfareporting.v1_2; using Google.Apis.Dfareporting.v1_2.Data; using Google.Apis.Samples.Helper; namespace DfaReporting.Sample { /// <summary> /// Lists all DFA user profiles associated with your Google Account. /// </summary> internal class GetAllUserProfilesHelper { private readonly DfareportingService service; /// <summary> /// Instantiate a helper for listing the DFA user profiles associated with your Google Account. /// </summary> /// <param name="service">DfaReporting service object used to run the requests.</param> public GetAllUserProfilesHelper(DfareportingService service) { this.service = service; } /// <summary> /// Runs this sample. /// </summary> /// <returns>The list of user profiles received.</returns> public UserProfileList Run() { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Listing all DFA user profiles"); CommandLine.WriteLine("================================================================="); // Retrieve DFA user profiles and display them. User profiles do not support // paging. var profiles = service.UserProfiles.List().Execute(); if (profiles.Items.Count > 0) { foreach (var profile in profiles.Items) { CommandLine.WriteLine("User profile with ID \"{0}\" and name \"{1}\" was found.", profile.ProfileId, profile.UserName); } } else { CommandLine.WriteLine("No profiles found."); } CommandLine.WriteLine(); return profiles; } } }
zzfocuzz-deepbotcopy
DfaReporting.Sample/GetAllUserProfilesHelper.cs
C#
asf20
2,521
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Drive.Sample")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google")] [assembly: AssemblyProduct("Drive.Sample")] [assembly: AssemblyCopyright("Copyright © Google 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("14001d69-d1ae-474b-9cd7-2a95731b8417")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-deepbotcopy
Drive.Sample/Properties/AssemblyInfo.cs
C#
asf20
1,448
<html> <title>Google .NET Client API &ndash; Drive.Sample</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Drive.Sample</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FDrive.Sample">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Drive.Sample/Program.cs?repo=samples">Program.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the Drive API</li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>Drive.Sample\bin\Debug</i></li> </ul> </body> </html>
zzfocuzz-deepbotcopy
Drive.Sample/README.html
HTML
asf20
1,433
/* Copyright 2013 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Threading.Tasks; using DotNetOpenAuth.OAuth2; using Google; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Download; using Google.Apis.Drive.v2; using Google.Apis.Drive.v2.Data; using Google.Apis.Logging; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Upload; using Google.Apis.Util; namespace Drive.Sample { /// <summary> /// A sample for the Drive API. This samples demonstrates resumable media upload and media download. /// See https://developers.google.com/drive/ for more details regarding the Drive API. /// </summary> class Program { static Program() { // initialize the log instance ApplicationContext.RegisterLogger(new Log4NetLogger()); Logger = ApplicationContext.Logger.ForType<ResumableUpload<Program>>(); } #region Consts private const int KB = 0x400; private const int DownloadChunkSize = 256 * KB; // CHANGE THIS with full path to the file you want to upload private const string UploadFileName = @"FILE_TO_UPLOAD_HERE"; // CHANGE THIS with a download directory private const string DownloadDirectoryName = @"DIRECTORY_TO_SAVE_THE_DOWNLOADED_MEDIA_HERE"; // CHANGE THIS if you upload a file type other than a jpg private const string ContentType = @"image/jpeg"; #endregion /// <summary>The logger instance.</summary> private static readonly ILogger Logger; /// <summary>The Drive API scopes.</summary> private static readonly string[] Scopes = new[] { DriveService.Scopes.DriveFile.GetStringValue(), DriveService.Scopes.Drive.GetStringValue() }; /// <summary> /// The file which was uploaded. We will use its download Url to download it using our media downloader object. /// </summary> private static File uploadedFile; static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("Drive API"); // Register the authenticator. FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials(); var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description) { ClientIdentifier = credentials.ClientId, ClientSecret = credentials.ClientSecret }; var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization); // Create the service. var service = new DriveService(new BaseClientService.Initializer() { Authenticator = auth, ApplicationName = "Drive API Sample", }); UploadFileAsync(service).ContinueWith(t => { // uploaded succeeded Console.WriteLine("\"{0}\" was uploaded successfully", uploadedFile.Title); DownloadFile(service, uploadedFile.DownloadUrl); DeleteFile(service, uploadedFile); }, TaskContinuationOptions.OnlyOnRanToCompletion); CommandLine.PressAnyKeyToExit(); } /// <summary>Uploads file asynchronously.</summary> private static Task<IUploadProgress> UploadFileAsync(DriveService service) { var title = UploadFileName; if (title.LastIndexOf('\\') != -1) { title = title.Substring(title.LastIndexOf('\\') + 1); } var uploadStream = new System.IO.FileStream(UploadFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); var insert = service.Files.Insert(new File { Title = title, }, uploadStream, ContentType); insert.ChunkSize = FilesResource.InsertMediaUpload.MinimumChunkSize * 2; insert.ProgressChanged += Upload_ProgressChanged; insert.ResponseReceived += Upload_ResponseReceived; var task = insert.UploadAsync(); task.ContinueWith(t => { // NotOnRanToCompletion - this code will be called if the upload fails Console.WriteLine("Upload Filed. " + t.Exception); }, TaskContinuationOptions.NotOnRanToCompletion); task.ContinueWith(t => { Logger.Debug("Closing the stream"); uploadStream.Dispose(); Logger.Debug("The stream was closed"); }); return task; } /// <summary>Downloads the media from the given URL.</summary> private static void DownloadFile(DriveService service, string url) { var downloader = new MediaDownloader(service); downloader.ChunkSize = DownloadChunkSize; // add a delegate for the progress changed event for writing to console on changes downloader.ProgressChanged += Download_ProgressChanged; // figure out the right file type base on UploadFileName extension var lastDot = UploadFileName.LastIndexOf('.'); var fileName = DownloadDirectoryName + @"\Download" + (lastDot != -1 ? "." + UploadFileName.Substring(lastDot + 1) : ""); using (var fileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { var progress = downloader.Download(url, fileStream); if (progress.Status == DownloadStatus.Completed) { Console.WriteLine(fileName + " was downloaded successfully"); } else { Console.WriteLine("Download {0} was interpreted in the middle. Only {1} were downloaded. ", fileName, progress.BytesDownloaded); } } } /// <summary>Deletes the given file from drive (not the file system).</summary> private static void DeleteFile(DriveService service, File file) { CommandLine.WriteLine("Deleting file '{0}'...", file.Id); service.Files.Delete(file.Id).Execute(); CommandLine.WriteLine("File was deleted successfully"); } #region Progress and Response changes static void Download_ProgressChanged(IDownloadProgress progress) { Console.WriteLine(progress.Status + " " + progress.BytesDownloaded); } static void Upload_ProgressChanged(IUploadProgress progress) { Console.WriteLine(progress.Status + " " + progress.BytesSent); } static void Upload_ResponseReceived(File file) { uploadedFile = file; } #endregion private static IAuthorizationState GetAuthorization(NativeApplicationClient client) { // You should use a more secure way of storing the key here as // .NET applications can be disassembled using a reflection tool. const string STORAGE = "google.samples.dotnet.drive"; const string KEY = "y},drdzf11x9;87"; // Check if there is a cached refresh token available. IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY); if (state != null) { try { client.RefreshToken(state); return state; // Yes - we are done. } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { CommandLine.WriteError("Using existing refresh token failed: " + ex.Message); } } // Retrieve the authorization from the user. state = AuthorizationMgr.RequestNativeAuthorization(client, Scopes); AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state); return state; } } }
zzfocuzz-deepbotcopy
Drive.Sample/Program.cs
C#
asf20
9,129
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Shopping.ListProducts")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google Inc")] [assembly: AssemblyProduct("Shopping.ListProducts")] [assembly: AssemblyCopyright("Copyright © Google Inc 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c445e21e-46f4-4682-91c2-af2424a70e7f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-deepbotcopy
Shopping.ListProducts/Properties/AssemblyInfo.cs
C#
asf20
1,474
<html> <title>Google .NET Client API &ndash; Shopping.ListProducts</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Shopping.ListProducts</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FShopping.ListProducts">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Shopping.ListProducts/Program.cs?repo=samples">Program.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the Shopping API for your project </li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>Shopping.ListProducts\bin\Debug</i></li> <li> When prompted insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane. </li> </ul> </body> </html>
zzfocuzz-deepbotcopy
Shopping.ListProducts/README.html
HTML
asf20
1,661
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Shopping.v1; using Google.Apis.Shopping.v1.Data; namespace Shopping.ListProducts { /// <summary> /// This sample uses the Shopping API to list a set of products. /// http://code.google.com/apis/shopping/search/v1/getting_started.html /// </summary> class Program { [STAThread] static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("Shopping API: List products"); // Create the service. var service = new ShoppingService(new BaseClientService.Initializer() { ApiKey = GetApiKey(), ApplicationName = "Shopping API Sample", }); RunSample(service); CommandLine.PressAnyKeyToExit(); } private static string GetApiKey() { return PromptingClientCredentials.EnsureSimpleClientCredentials().ApiKey; } static void RunSample(ShoppingService service) { // Build the request. string query = "Camera"; CommandLine.RequestUserInput("Product to search for", ref query); CommandLine.WriteLine(); CommandLine.WriteAction("Executing request ..."); var request = service.Products.List("public"); request.Country = "us"; request.Q = query; // Parse the response. long startIndex = 1; do { request.StartIndex = startIndex; Products response = request.Execute(); if (response.CurrentItemCount == 0) { break; // Nothing more to list. } // Show the items. foreach (Product item in response.Items) { CommandLine.WriteResult((startIndex++) + ". Result", item.ProductValue.Title.TrimByLength(60)); } } while (CommandLine.RequestUserChoice("Do you want to see more items?")); } } }
zzfocuzz-deepbotcopy
Shopping.ListProducts/Program.cs
C#
asf20
2,924
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("UrlShortener.ListURLs")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google Inc")] [assembly: AssemblyProduct("UrlShortener.ListURLs")] [assembly: AssemblyCopyright("Copyright © Google Inc 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a9aca0ea-7fb7-44ee-8874-dcc4519ffe0d")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-deepbotcopy
UrlShortener.ListURLs/Properties/AssemblyInfo.cs
C#
asf20
1,434
<html> <title>Google .NET Client API &ndash; UrlShortener.ListURLs</title> <body> <h2>Instructions for the Google .NET Client API &ndash; UrlShortener.ListURLs</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FUrlShortener.ListURLs">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/UrlShortener.ListURLs/Program.cs?repo=samples">Program.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the UrlShortener API for your project </li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>UrlShortener.ListURLs\bin\Debug</i></li> <li> When prompted insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane. </li> </ul> </body> </html>
zzfocuzz-deepbotcopy
UrlShortener.ListURLs/README.html
HTML
asf20
1,665
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using DotNetOpenAuth.OAuth2; using Google.Apis.Authentication; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Urlshortener.v1; using Google.Apis.Urlshortener.v1.Data; using Google.Apis.Util; namespace UrlShortener.ListURLs { /// <summary> /// URLShortener OAuth2 Sample /// /// This sample uses OAuth2 to retrieve a list of all the URL's you have shortened so far. /// </summary> internal class Program { private static readonly string Scope = UrlshortenerService.Scopes.Urlshortener.GetStringValue(); static void Main(string[] args) { // Initialize this sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("URLShortener -- List URLs"); // Register the authenticator. FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials(); var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description) { ClientIdentifier = credentials.ClientId, ClientSecret = credentials.ClientSecret, }; var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization); // Create the service. var service = new UrlshortenerService(new BaseClientService.Initializer() { Authenticator = auth, ApplicationName = "UrlShortener API Sample", }); // List all shortened URLs: CommandLine.WriteAction("Retrieving list of shortened urls..."); int i = 0; string nextPageToken = null; do { // Create and execute the request. var request = service.Url.List(); request.StartToken = nextPageToken; UrlHistory result = request.Execute(); // List all items on this page. if (result.Items != null) { foreach (Url item in result.Items) { CommandLine.WriteResult((++i) + ".) URL", item.Id + " -> " + item.LongUrl); } } // Continue with the next page nextPageToken = result.NextPageToken; } while (!string.IsNullOrEmpty(nextPageToken)); if (i == 0) { CommandLine.WriteAction("You don't have any shortened URLs! Visit http://goo.gl and create some."); } // ... and we are done. CommandLine.PressAnyKeyToExit(); } private static IAuthorizationState GetAuthorization(NativeApplicationClient client) { // You should use a more secure way of storing the key here as // .NET applications can be disassembled using a reflection tool. const string STORAGE = "google.samples.dotnet.urlshortener"; const string KEY = "S7Uf8AsapUWrac798uga5U8e5azePhAf"; // Check if there is a cached refresh token available. IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY); if (state != null) { try { client.RefreshToken(state); return state; // Yes - we are done. } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { CommandLine.WriteError("Using existing refresh token failed: " + ex.Message); } } // Retrieve the authorization from the user. state = AuthorizationMgr.RequestNativeAuthorization(client, Scope); AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state); return state; } } }
zzfocuzz-deepbotcopy
UrlShortener.ListURLs/Program.cs
C#
asf20
4,769
<html> <title>Google .NET Client API &ndash; Samples solution</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Samples solution</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse?repo=samples">Browse Source</a> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio or <a href="http://monodevelop.com/">MonoDevelop</a>, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the APIs you want to use </li> <li>Enter your client credentials by executing enterCredentials.cmd (or running "chmod +x configure && ./configure" on Unix) You can find your credentials on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane.</li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Pick a sample, and execute the .exe in <i>&lt;SampleDir&gt;\bin\Debug</i></li> </ul> <h3>Setup Project in MonoDevelop</h3> <ul> <li>Open the GoogleApisSamples_mono.sln with MonoDevelop</li> <li>Click on Build &gt; Rebuild All</li> <li>Pick a sample, and execute the .exe in <i>&lt;SampleDir&gt;\bin\Debug</i> using mono</li> </ul> </body> </html>
zzfocuzz-deepbotcopy
README.html
HTML
asf20
1,854
Imports System Imports System.Reflection Imports System.Runtime.InteropServices ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes <Assembly: AssemblyTitle("Discovery.VB.ListAPIs")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("Microsoft")> <Assembly: AssemblyProduct("Discovery.VB.ListAPIs")> <Assembly: AssemblyCopyright("Copyright © Microsoft 2011")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("1dce71e9-b3b6-452e-9fb3-011567ea293f")> ' Version information for an assembly consists of the following four values: ' ' Major Version ' Minor Version ' Build Number ' Revision ' ' You can specify all the values or you can default the Build and Revision Numbers ' by using the '*' as shown below: ' <Assembly: AssemblyVersion("1.0.*")> <Assembly: AssemblyVersion("1.0.0.0")> <Assembly: AssemblyFileVersion("1.0.0.0")>
zzfocuzz-deepbotcopy
Discovery.VB.ListAPIs/My Project/AssemblyInfo.vb
Visual Basic .NET
asf20
1,213
'Copyright 2011 Google Inc ' 'Licensed under the Apache License, Version 2.0(the "License"); 'you may not use this file except in compliance with the License. 'You may obtain a copy of the License at ' ' http://www.apache.org/licenses/LICENSE-2.0 ' 'Unless required by applicable law or agreed to in writing, software 'distributed under the License is distributed on an "AS IS" BASIS, 'WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 'See the License for the specific language governing permissions and 'limitations under the License. ' Imports Google.Apis.Discovery.v1 Imports Google.Apis.Discovery.v1.Data Imports Google.Apis.Samples.Helper ''' <summary> ''' This example uses the discovery API to list all APIs in the discovery repository. ''' http://code.google.com/apis/discovery/v1/using.html ''' </summary> Class Program Shared Sub Main() ' Display the header and initialize the sample. CommandLine.EnableExceptionHandling() CommandLine.DisplayGoogleSampleHeader("Discovery API") ' Create the service. Dim service = New DiscoveryService() RunSample(service) CommandLine.PressAnyKeyToExit() End Sub Private Shared Sub RunSample(ByVal service As DiscoveryService) ' Run the request. CommandLine.WriteAction("Executing List-request ...") Dim result = service.Apis.List().Execute() ' Display the results. If result.Items IsNot Nothing Then For Each api As DirectoryList.ItemsData In result.Items CommandLine.WriteResult(api.Id, api.Title) Next End If End Sub End Class
zzfocuzz-deepbotcopy
Discovery.VB.ListAPIs/Program.vb
Visual Basic .NET
asf20
1,714
<html> <title>Google .NET Client API &ndash; Discovery.VB.ListAPIs</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Discovery.VB.ListAPIs</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FDiscovery.VB.ListAPIs">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Discovery.VB.ListAPIs/Program.vb?repo=samples">Program.vb</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>Discovery.VB.ListAPIs\bin\Debug</i></li> </ul> </body> </html>
zzfocuzz-deepbotcopy
Discovery.VB.ListAPIs/README.html
HTML
asf20
1,064
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Prediction.Simple")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google Inc")] [assembly: AssemblyProduct("Prediction.Simple")] [assembly: AssemblyCopyright("Copyright © Google Inc 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a3949ef2-c68f-4ef2-a809-222418766e4e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-deepbotcopy
Prediction.Simple/Properties/AssemblyInfo.cs
C#
asf20
1,466
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using Google.Apis.Samples.Helper; namespace Prediction.Simple { /// <summary> /// This class provides the client credentials for all the samples in this solution. /// In order to run all of the samples, you have to enable API access for every API /// you want to use, enter your credentials here. /// /// You can find your credentials here: /// https://code.google.com/apis/console/#:access /// /// For your own application you should find a more secure way than just storing your client secret inside a string, /// as it can be lookup up easily using a reflection tool. /// </summary> internal static class ClientCredentials { /// <summary> /// The OAuth2.0 Client ID of your project. /// </summary> public static readonly string ClientID = "<Enter your ClientID here>"; /// <summary> /// The OAuth2.0 Client secret of your project. /// </summary> public static readonly string ClientSecret = "<Enter your ClientSecret here>"; /// <summary> /// Your Google-storage bucket, and the file which is used for prediction. /// </summary> public static readonly string BucketPath = "<My Bucket>/language_id.txt"; #region Verify Credentials static ClientCredentials() { ReflectionUtils.VerifyCredentials(typeof(ClientCredentials)); } #endregion } }
zzfocuzz-deepbotcopy
Prediction.Simple/ClientCredentials.cs
C#
asf20
2,066
<html> <title>Google .NET Client API &ndash; Prediction.Simple</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Prediction.Simple</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FPrediction.Simple">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Prediction.Simple/Program.cs?repo=samples">Program.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the Prediction API and Google Storage for your project </li> <li>Edit <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Prediction.Simple/ClientCredentials.cs?repo=samples">ClientCredentials.cs</a> to insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane.</li> </ul> </p> <h3>3. Uploading a file containing prediction data</h3> In order to predict something, you first have to upload a file containing prediction data and train the system. This project contains a simple sample set of data, <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Prediction.Simple/language_id.txt?repo=samples">language_id.txt</a>, which you can upload to <a href="https://code.google.com/apis/console/b/0/#project:storage:access">Google Storage</a>. <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>Prediction.Simple\bin\Debug</i></li> </ul> </body> </html>
zzfocuzz-deepbotcopy
Prediction.Simple/README.html
HTML
asf20
2,279
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Threading; using DotNetOpenAuth.OAuth2; using Google.Apis.Authentication; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Prediction.v1_3; using Google.Apis.Prediction.v1_3.Data; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Util; namespace Prediction.Simple { /// <summary> /// Sample for the prediction API. /// This sample trains a simple model, and makes a prediction on the user input. /// /// This sample requires you to have the file specified in ClientCredentials.cs uploaded to Google-Storage. /// Instructions on enabling G-Storage: http://code.google.com/apis/storage/docs/signup.html /// </summary> internal class Program { [STAThread] static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("Prediction API"); CommandLine.WriteLine(); // Register the authenticator. var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description) { ClientIdentifier = ClientCredentials.ClientID, ClientSecret = ClientCredentials.ClientSecret }; var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication); // Create the service. var service = new PredictionService(new BaseClientService.Initializer() { Authenticator = auth, ApplicationName = "Prediction API Sample", }); RunPrediction(service); CommandLine.PressAnyKeyToExit(); } private static IAuthorizationState GetAuthentication(NativeApplicationClient client) { // You should use a more secure way of storing the key here as // .NET applications can be disassembled using a reflection tool. const string STORAGE = "google.samples.dotnet.prediction"; const string KEY = "AF41sdBra7ufra)VD:@#A#a++=3e"; string scope = PredictionService.Scopes.Prediction.GetStringValue(); // Check if there is a cached refresh token available. IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY); if (state != null) { try { client.RefreshToken(state); return state; // Yes - we are done. } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { CommandLine.WriteError("Using existing refresh token failed: " + ex.Message); } } // Retrieve the authorization from the user. state = AuthorizationMgr.RequestNativeAuthorization(client, scope); AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state); return state; } private static void RunPrediction(PredictionService service) { // Train the service with the existing bucket data. string id = ClientCredentials.BucketPath; CommandLine.WriteAction("Performing training of the service ..."); CommandLine.WriteResult("Bucket", id); Training training = new Training { Id = id }; training = service.Training.Insert(training).Execute(); // Wait until the training is complete. while (training.TrainingStatus == "RUNNING") { CommandLine.Write(".."); Thread.Sleep(1000); training = service.Training.Get(id).Execute(); } CommandLine.WriteLine(); CommandLine.WriteAction("Training complete!"); CommandLine.WriteLine(); // Make a prediction. CommandLine.WriteAction("Performing a prediction..."); string text = "mucho bueno"; CommandLine.RequestUserInput("Text to analyze", ref text); var input = new Input { InputValue = new Input.InputData { CsvInstance = new List<string> { text } } }; Output result = service.Training.Predict(input, id).Execute(); CommandLine.WriteResult("Language", result.OutputLabel); } } }
zzfocuzz-deepbotcopy
Prediction.Simple/Program.cs
C#
asf20
5,243
<?php // vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: /** * Parse structured wiki text and render into arbitrary formats such as XHTML. * * PHP versions 4 and 5 * * @category Text * @package Text_Wiki * @author Paul M. Jones <pmjones@php.net> * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1 * @version CVS: $Id: Creole_Wiki.php 182 2008-09-14 15:56:00Z i.feelinglucky $ * @link http://pear.php.net/package/Text_Wiki */ /** * The baseline abstract parser class. */ require_once 'Parse.inc.php'; /** * The baseline abstract render class. */ require_once 'Render.inc.php'; /** * Parse structured wiki text and render into arbitrary formats such as XHTML. * * This is the "master" class for handling the management and convenience * functions to transform Wiki-formatted text. * * @category Text * @package Text_Wiki * @author Paul M. Jones <pmjones@php.net> * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1 * @version Release: 1.2.0 * @link http://pear.php.net/package/Text_Wiki */ class Creole_Wiki { // *single newlines* are handled as in most wikis (ignored) // if Newline is removed from rules, they will be handled as in word-processors (meaning a paragraph break) protected $rules = array( 'Prefilter', 'Delimiter', 'Preformatted', 'Zzcode', 'Tt', //'Trim', 'Break', 'Raw', 'Box', //'Footnote', 'Table', 'Newline', 'Blockquote', 'Newline', //'Wikilink', 'Heading', 'Center', 'Horiz', 'List', 'Address', 'Paragraph', 'Superscript', 'Subscript', 'Underline', 'Strong', 'Tighten', 'Image', 'Url', 'Emphasis' ); /** * * The list of rules to not-apply to the source text. * * @access public * * @var array * */ public $disable = array( 'Html', 'Include', 'Embed' ); /** * * Custom configuration for rules at the parsing stage. * * In this array, the key is the parsing rule name, and the value is * an array of key-value configuration pairs corresponding to the $conf * property in the target parsing rule. * * For example: * * <code> * $parseConf = array( * 'Include' => array( * 'base' => '/path/to/scripts/' * ) * ); * </code> * * Note that most default rules do not need any parsing configuration. * * @access public * * @var array * */ public $parseConf = array(); /** * * Custom configuration for rules at the rendering stage. * * Because rendering may be different for each target format, the * first-level element in this array is always a format name (e.g., * 'Xhtml'). * * Within that first level element, the subsequent elements match the * $parseConf format. That is, the sub-key is the rendering rule name, * and the sub-value is an array of key-value configuration pairs * corresponding to the $conf property in the target rendering rule. * * @access public * * @var array * */ public $renderConf = array( 'Docbook' => array(), 'Latex' => array(), 'Pdf' => array(), 'Plain' => array(), 'Rtf' => array(), 'Xhtml' => array() ); /** * * Custom configuration for the output format itself. * * Even though Text_Wiki will render the tokens from parsed text, * the format itself may require some configuration. For example, * RTF needs to know font names and sizes, PDF requires page layout * information, and DocBook needs a section hierarchy. This array * matches the $conf property of the the format-level renderer * (e.g., Text_Wiki_Render_Xhtml). * * In this array, the key is the rendering format name, and the value is * an array of key-value configuration pairs corresponding to the $conf * property in the rendering format rule. * * @access public * * @var array * */ public $formatConf = array( 'Docbook' => array(), 'Latex' => array(), 'Pdf' => array(), 'Plain' => array(), 'Rtf' => array(), 'Xhtml' => array() ); /** * * The delimiter for token numbers of parsed elements in source text. * * @access public * * @var string * */ public $delim = "\xFF"; /** * * The tokens generated by rules as the source text is parsed. * * As Text_Wiki applies rule classes to the source text, it will * replace portions of the text with a delimited token number. This * is the array of those tokens, representing the replaced text and * any options set by the parser for that replaced text. * * The tokens array is sequential; each element is itself a sequential * array where element 0 is the name of the rule that generated the * token, and element 1 is an associative array where the key is an * option name and the value is an option value. * * @access private * * @var array * */ public $tokens = array(); /** * How many tokens generated pro rules. * * Intended to load only necessary render objects * * @access private * @var array */ private $_countRulesTokens = array(); /** * * The source text to which rules will be applied. * * This text will be transformed in-place, which means that it will * change as the rules are applied. * * @access public * * @var string * */ public $source = ''; /** * The output text * * @var string */ protected $output = ''; /** * * Array of rule parsers. * * Text_Wiki creates one instance of every rule that is applied to * the source text; this array holds those instances. The array key * is the rule name, and the array value is an instance of the rule * class. * * @access private * * @var array * */ protected $parseObj = array(); /** * * Array of rule renderers. * * Text_Wiki creates one instance of every rule that is applied to * the source text; this array holds those instances. The array key * is the rule name, and the array value is an instance of the rule * class. * * @access private * * @var array * */ protected $renderObj = array(); /** * * Array of format renderers. * * @access private * * @var array * */ protected $formatObj = array(); /** * * Array of paths to search, in order, for parsing and rendering rules. * * @access private * * @var array * */ protected $path = array( 'parse' => array(), 'render' => array() ); /** * * The directory separator character. * * @access private * * @var string * */ private $_dirSep = DIRECTORY_SEPARATOR; /** * Temporary configuration variable * * @var string */ protected $renderingType = 'preg'; /** * Stack of rendering callbacks * * @var Array */ private $_renderCallbacks = array(); /** * Current output block * * @var string */ private $_block; /** * A stack of blocks * * @param Array */ private $_blocks; /** * * Constructor. * * **DEPRECATED** * Please use the singleton() or factory() methods. * * @access public * * @param array $rules The set of rules to load for this object. Defaults * to null, which will load the default ruleset for this parser. */ function __construct($rules = null) { if (is_array($rules)) { $this->rules = array(); foreach ($rules as $rule) { $this->rules[] = ucfirst($rule); } } /* $this->addPath( 'parse', $this->fixPath(dirname(__FILE__)) . 'Wiki/Parse/Default/' ); */ $this->addPath( 'parse', $this->fixPath(dirname(__FILE__) . '/Parse/') ); $this->addPath( 'render', $this->fixPath(dirname(__FILE__) . '/Render/' ) ); $this->renderingType = 'char'; $this->setRenderConf('xhtml', 'center', 'css', 'center'); $this->setRenderConf('xhtml', 'url', 'target', null); } /** * Singleton. * * This avoids instantiating multiple Text_Wiki instances where a number * of objects are required in one call, e.g. to save memory in a * CMS invironment where several parsers are required in a single page. * * $single = & singleton(); * * or * * $single = & singleton('Parser', array('Prefilter', 'Delimiter', 'Code', 'Function', * 'Html', 'Raw', 'Include', 'Embed', 'Anchor', 'Heading', 'Toc', 'Horiz', * 'Break', 'Blockquote', 'List', 'Deflist', 'Table', 'Image', 'Phplookup', * 'Center', 'Newline', 'Paragraph', 'Url', 'Freelink', 'Interwiki', 'Wikilink', * 'Colortext', 'Strong', 'Bold', 'Emphasis', 'Italic', 'Underline', 'Tt', * 'Superscript', 'Subscript', 'Revise', 'Tighten')); * * Call using a subset of this list. The order of passing rulesets in the * $rules array is important! * * After calling this, call $single->setParseConf(), setRenderConf() or setFormatConf() * as usual for a constructed object of this class. * * The internal static array of singleton objects has no index on the parser * rules, the only index is on the parser name. So if you call this multiple * times with different rules but the same parser name, you will get the same * static parser object each time. * * @access public * @static * @since Method available since Release 1.1.0 * @param string $parser The parser to be used (defaults to 'Default'). * @param array $rules The set of rules to instantiate the object. This * will only be used when the first call to singleton is made, if included * in further calls it will be effectively ignored. * @return &object a reference to the Text_Wiki unique instantiation. */ /* public function &singleton($parser = 'Default', $rules = null) { static $only = array(); if (!isset($only[$parser])) { $ret = & Text_Wiki::factory($parser, $rules); if (Text_Wiki::isError($ret)) { return $ret; } $only[$parser] =& $ret; } return $only[$parser]; } */ /** * Returns a Text_Wiki Parser class for the specified parser. * * @access public * @static * @param string $parser The name of the parse to instantiate * you need to have Text_Wiki_XXX installed to use $parser = 'XXX', it's E_FATAL * @param array $rules The rules to pass into the constructor * {@see Text_Wiki::singleton} for a list of rules * @return Text_Wiki a Parser object extended from Text_Wiki */ /* public function &factory($parser = 'Default', $rules = null) { $class = 'Text_Wiki_' . ucfirst(strtolower($parser)); $file = str_replace('_', '/', $class).'.php'; if (!class_exists($class)) { require_once $file; if (!class_exists($class)) { return Text_Wiki::error( 'Class ' . $class . ' does not exist after requiring '. $file . ', install package ' . $class . "\n"); } } $obj =& new $class($rules); return $obj; } */ /** * * Set parser configuration for a specific rule and key. * * @access public * * @param string $rule The parse rule to set config for. * * @param array|string $arg1 The full config array to use for the * parse rule, or a conf key in that array. * * @param string $arg2 The config value for the key. * * @return void * */ public function setParseConf($rule, $arg1, $arg2 = null) { $rule = ucwords(strtolower($rule)); if (! isset($this->parseConf[$rule])) { $this->parseConf[$rule] = array(); } // if first arg is an array, use it as the entire // conf array for the rule. otherwise, treat arg1 // as a key and arg2 as a value for the rule conf. if (is_array($arg1)) { $this->parseConf[$rule] = $arg1; } else { $this->parseConf[$rule][$arg1] = $arg2; } } /** * * Get parser configuration for a specific rule and key. * * @access public * * @param string $rule The parse rule to get config for. * * @param string $key A key in the conf array; if null, * returns the entire conf array. * * @return mixed The whole conf array if no key is specified, * or the specific conf key value. * */ public function getParseConf($rule, $key = null) { $rule = ucwords(strtolower($rule)); // the rule does not exist if (! isset($this->parseConf[$rule])) { return null; } // no key requested, return the whole array if (is_null($key)) { return $this->parseConf[$rule]; } // does the requested key exist? if (isset($this->parseConf[$rule][$key])) { // yes, return that value return $this->parseConf[$rule][$key]; } else { // no return null; } } /** * * Set renderer configuration for a specific format, rule, and key. * * @access public * * @param string $format The render format to set config for. * * @param string $rule The render rule to set config for in the format. * * @param array|string $arg1 The config array, or the config key * within the render rule. * * @param string $arg2 The config value for the key. * * @return void * */ function setRenderConf($format, $rule, $arg1, $arg2 = null) { $format = ucwords(strtolower($format)); $rule = ucwords(strtolower($rule)); if (! isset($this->renderConf[$format])) { $this->renderConf[$format] = array(); } if (! isset($this->renderConf[$format][$rule])) { $this->renderConf[$format][$rule] = array(); } // if first arg is an array, use it as the entire // conf array for the render rule. otherwise, treat arg1 // as a key and arg2 as a value for the render rule conf. if (is_array($arg1)) { $this->renderConf[$format][$rule] = $arg1; } else { $this->renderConf[$format][$rule][$arg1] = $arg2; } } /** * * Get renderer configuration for a specific format, rule, and key. * * @access public * * @param string $format The render format to get config for. * * @param string $rule The render format rule to get config for. * * @param string $key A key in the conf array; if null, * returns the entire conf array. * * @return mixed The whole conf array if no key is specified, * or the specific conf key value. * */ function getRenderConf($format, $rule, $key = null) { $format = ucwords(strtolower($format)); $rule = ucwords(strtolower($rule)); if (! isset($this->renderConf[$format]) || ! isset($this->renderConf[$format][$rule])) { return null; } // no key requested, return the whole array if (is_null($key)) { return $this->renderConf[$format][$rule]; } // does the requested key exist? if (isset($this->renderConf[$format][$rule][$key])) { // yes, return that value return $this->renderConf[$format][$rule][$key]; } else { // no return null; } } /** * * Set format configuration for a specific rule and key. * * @access public * * @param string $format The format to set config for. * * @param string $key The config key within the format. * * @param string $val The config value for the key. * * @return void * */ function setFormatConf($format, $arg1, $arg2 = null) { if (! is_array($this->formatConf[$format])) { $this->formatConf[$format] = array(); } // if first arg is an array, use it as the entire // conf array for the format. otherwise, treat arg1 // as a key and arg2 as a value for the format conf. if (is_array($arg1)) { $this->formatConf[$format] = $arg1; } else { $this->formatConf[$format][$arg1] = $arg2; } } /** * * Get configuration for a specific format and key. * * @access public * * @param string $format The format to get config for. * * @param mixed $key A key in the conf array; if null, * returns the entire conf array. * * @return mixed The whole conf array if no key is specified, * or the specific conf key value. * */ function getFormatConf($format, $key = null) { // the format does not exist if (! isset($this->formatConf[$format])) { return null; } // no key requested, return the whole array if (is_null($key)) { return $this->formatConf[$format]; } // does the requested key exist? if (isset($this->formatConf[$format][$key])) { // yes, return that value return $this->formatConf[$format][$key]; } else { // no return null; } } /** * * Inserts a rule into to the rule set. * * @access public * * @param string $name The name of the rule. Should be different from * all other keys in the rule set. * * @param string $tgt The rule after which to insert this new rule. By * default (null) the rule is inserted at the end; if set to '', inserts * at the beginning. * * @return void * */ function insertRule($name, $tgt = null) { $name = ucwords(strtolower($name)); if (! is_null($tgt)) { $tgt = ucwords(strtolower($tgt)); } // does the rule name to be inserted already exist? if (in_array($name, $this->rules)) { // yes, return return null; } // the target name is not null, and not '', but does not exist // in the list of rules. this means we're trying to insert after // a target key, but the target key isn't there. if (! is_null($tgt) && $tgt != '' && ! in_array($tgt, $this->rules)) { return false; } // if $tgt is null, insert at the end. We know this is at the // end (instead of resetting an existing rule) becuase we exited // at the top of this method if the rule was already in place. if (is_null($tgt)) { $this->rules[] = $name; return true; } // save a copy of the current rules, then reset the rule set // so we can insert in the proper place later. // where to insert the rule? if ($tgt == '') { // insert at the beginning array_unshift($this->rules, $name); return true; } // insert after the named rule $tmp = $this->rules; $this->rules = array(); foreach ($tmp as $val) { $this->rules[] = $val; if ($val == $tgt) { $this->rules[] = $name; } } return true; } /** * * Delete (remove or unset) a rule from the $rules property. * * @access public * * @param string $rule The name of the rule to remove. * * @return void * */ function deleteRule($name) { $name = ucwords(strtolower($name)); $key = array_search($name, $this->rules); if ($key !== false) { unset($this->rules[$key]); } } /** * * Change from one rule to another in-place. * * @access public * * @param string $old The name of the rule to change from. * * @param string $new The name of the rule to change to. * * @return void * */ function changeRule($old, $new) { $old = ucwords(strtolower($old)); $new = ucwords(strtolower($new)); $key = array_search($old, $this->rules); if ($key !== false) { // delete the new name , case it was already there $this->deleteRule($new); $this->rules[$key] = $new; } } /** * * Enables a rule so that it is applied when parsing. * * @access public * * @param string $rule The name of the rule to enable. * * @return void * */ function enableRule($name) { $name = ucwords(strtolower($name)); $key = array_search($name, $this->disable); if ($key !== false) { unset($this->disable[$key]); } } /** * * Disables a rule so that it is not applied when parsing. * * @access public * * @param string $rule The name of the rule to disable. * * @return void * */ function disableRule($name) { $name = ucwords(strtolower($name)); $key = array_search($name, $this->disable); if ($key === false) { $this->disable[] = $name; } } /** * * Parses and renders the text passed to it, and returns the results. * * First, the method parses the source text, applying rules to the * text as it goes. These rules will modify the source text * in-place, replacing some text with delimited tokens (and * populating the $this->tokens array as it goes). * * Next, the method renders the in-place tokens into the requested * output format. * * Finally, the method returns the transformed text. Note that the * source text is transformed in place; once it is transformed, it is * no longer the same as the original source text. * * @access public * * @param string $text The source text to which wiki rules should be * applied, both for parsing and for rendering. * * @param string $format The target output format, typically 'xhtml'. * If a rule does not support a given format, the output from that * rule is rule-specific. * * @return string The transformed wiki text. * */ function transform($text, $format = 'Xhtml') { $this->parse($text); return $this->render($format); } /** * * Sets the $_source text property, then parses it in place and * retains tokens in the $_tokens array property. * * @access public * * @param string $text The source text to which wiki rules should be * applied, both for parsing and for rendering. * * @return void * */ function parse($text) { // set the object property for the source text $this->source = $text; // reset the tokens. $this->tokens = array(); $this->_countRulesTokens = array(); // apply the parse() method of each requested rule to the source // text. foreach ($this->rules as $name) { // do not parse the rules listed in $disable if (! in_array($name, $this->disable)) { // load the parsing object $this->loadParseObj($name); // load may have failed; only parse if // an object is in the array now if (is_object($this->parseObj[$name])) { $this->parseObj[$name]->parse(); } } } } /** * * Renders tokens back into the source text, based on the requested format. * * @access public * * @param string $format The target output format, typically 'xhtml'. * If a rule does not support a given format, the output from that * rule is rule-specific. * * @return string The transformed wiki text. * */ function render($format = 'Xhtml') { // the rendering method we're going to use from each rule $format = ucwords(strtolower($format)); // the eventual output text $this->output = ''; // when passing through the parsed source text, keep track of when // we are in a delimited section $in_delim = false; // when in a delimited section, capture the token key number $key = ''; // load the format object, or crap out if we can't find it $result = $this->loadFormatObj($format); if ($this->isError($result)) { return $result; } /* * hunked by feelinglucky.. // pre-rendering activity if (is_object($this->formatObj[$format])) { $this->output .= $this->formatObj[$format]->pre(); } */ // load the render objects foreach (array_keys($this->_countRulesTokens) as $rule) { $this->loadRenderObj($format, $rule); } if ($this->renderingType == 'preg') { $this->output = preg_replace_callback('/'.$this->delim.'(\d+)'.$this->delim.'/', array(&$this, '_renderToken'), $this->source); /* //Damn strtok()! Why does it "skip" empty parts of the string. It's useless now! } elseif ($this->renderingType == 'strtok') { echo '<pre>'.htmlentities($this->source).'</pre>'; $t = strtok($this->source, $this->delim); $inToken = true; $i = 0; while ($t !== false) { echo 'Token: '.$i.'<pre>"'.htmlentities($t).'"</pre><br/><br/>'; if ($inToken) { //$this->output .= $this->renderObj[$this->tokens[$t][0]]->token($this->tokens[$t][1]); } else { $this->output .= $t; } $inToken = !$inToken; $t = strtok($this->delim); ++$i; } */ } else { // pass through the parsed source text character by character $this->_block = ''; $tokenStack = array(); $k = strlen($this->source); for ($i = 0; $i < $k; $i++) { // the current character $char = $this->source{$i}; // are alredy in a delimited section? if ($in_delim) { // yes; are we ending the section? if ($char == $this->delim) { if (count($this->_renderCallbacks) == 0) { $this->output .= $this->_block; $this->_block = ''; } if (isset($opts['type'])) { if ($opts['type'] == 'start') { array_push($tokenStack, $rule); } elseif ($opts['type'] == 'end') { if ($tokenStack[count($tokenStack) - 1] != $rule) { return Text_Wiki::error('Unbalanced tokens, check your syntax'); } else { array_pop($tokenStack); } } } // yes, get the replacement text for the delimited // token number and unset the flag. $key = (int)$key; $rule = $this->tokens[$key][0]; $opts = $this->tokens[$key][1]; $this->_block .= $this->renderObj[$rule]->token($opts); $in_delim = false; } else { // no, add to the delimited token key number $key .= $char; } } else { // not currently in a delimited section. // are we starting into a delimited section? if ($char == $this->delim) { // yes, reset the previous key and // set the flag. $key = ''; $in_delim = true; } else { // no, add to the output as-is $this->_block .= $char; } } } } if (count($this->_renderCallbacks)) { return $this->error('Render callbacks left over after processing finished'); } /* while (count($this->_renderCallbacks)) { $this->popRenderCallback(); } */ if (strlen($this->_block)) { $this->output .= $this->_block; $this->_block = ''; } /* tunk by feelinglucky // post-rendering activity if (is_object($this->formatObj[$format])) { $this->output .= $this->formatObj[$format]->post(); } */ // return the rendered source text. return $this->output; } /** * Renders a token, for use only as an internal callback * * @param array Matches from preg_rpelace_callback, [1] is the token number * @return string The rendered text for the token * @access private */ function _renderToken($matches) { return $this->renderObj[$this->tokens[$matches[1]][0]]->token($this->tokens[$matches[1]][1]); } function registerRenderCallback($callback) { $this->_blocks[] = $this->_block; $this->_block = ''; $this->_renderCallbacks[] = $callback; } function popRenderCallback() { if (count($this->_renderCallbacks) == 0) { return Text_Wiki::error('Render callback popped when no render callbacks in stack'); } else { $callback = array_pop($this->_renderCallbacks); $this->_block = call_user_func($callback, $this->_block); if (count($this->_blocks)) { $parentBlock = array_pop($this->_blocks); $this->_block = $parentBlock.$this->_block; } if (count($this->_renderCallbacks) == 0) { $this->output .= $this->_block; $this->_block = ''; } } } /** * * Returns the parsed source text with delimited token placeholders. * * @access public * * @return string The parsed source text. * */ function getSource() { return $this->source; } /** * * Returns tokens that have been parsed out of the source text. * * @access public * * @param array $rules If an array of rule names is passed, only return * tokens matching these rule names. If no array is passed, return all * tokens. * * @return array An array of tokens. * */ function getTokens($rules = null) { if (is_null($rules)) { return $this->tokens; } else { settype($rules, 'array'); $result = array(); foreach ($this->tokens as $key => $val) { if (in_array($val[0], $rules)) { $result[$key] = $val; } } return $result; } } /** * * Add a token to the Text_Wiki tokens array, and return a delimited * token number. * * @access public * * @param array $options An associative array of options for the new * token array element. The keys and values are specific to the * rule, and may or may not be common to other rule options. Typical * options keys are 'text' and 'type' but may include others. * * @param boolean $id_only If true, return only the token number, not * a delimited token string. * * @return string|int By default, return the number of the * newly-created token array element with a delimiter prefix and * suffix; however, if $id_only is set to true, return only the token * number (no delimiters). * */ function addToken($rule, $options = array(), $id_only = false) { // increment the token ID number. note that if you parse // multiple times with the same Text_Wiki object, the ID number // will not reset to zero. static $id; if (! isset($id)) { $id = 0; } else { $id ++; } // force the options to be an array settype($options, 'array'); // add the token $this->tokens[$id] = array( 0 => $rule, 1 => $options ); if (!isset($this->_countRulesTokens[$rule])) { $this->_countRulesTokens[$rule] = 1; } else { ++$this->_countRulesTokens[$rule]; } // return a value if ($id_only) { // return the last token number return $id; } else { // return the token number with delimiters return $this->delim . $id . $this->delim; } } /** * * Set or re-set a token with specific information, overwriting any * previous rule name and rule options. * * @access public * * @param int $id The token number to reset. * * @param int $rule The rule name to use. * * @param array $options An associative array of options for the * token array element. The keys and values are specific to the * rule, and may or may not be common to other rule options. Typical * options keys are 'text' and 'type' but may include others. * * @return void * */ function setToken($id, $rule, $options = array()) { $oldRule = $this->tokens[$id][0]; // reset the token $this->tokens[$id] = array( 0 => $rule, 1 => $options ); if ($rule != $oldRule) { if (!($this->_countRulesTokens[$oldRule]--)) { unset($this->_countRulesTokens[$oldRule]); } if (!isset($this->_countRulesTokens[$rule])) { $this->_countRulesTokens[$rule] = 1; } else { ++$this->_countRulesTokens[$rule]; } } } /** * * Load a rule parser class file. * * @access public * * @return bool True if loaded, false if not. * */ function loadParseObj($rule) { $rule = ucwords(strtolower($rule)); $file = $rule . '.php'; $class = "Text_Wiki_Parse_$rule"; if (!Typecho_Common::isAvailableClass($class)) { $loc = $this->findFile('parse', $file); if ($loc) { // found the class include_once $loc; } else { // can't find the class $this->parseObj[$rule] = null; // can't find the class return $this->error( "Parse rule '$rule' not found" ); } } $this->parseObj[$rule] = new $class($this); } /** * * Load a rule-render class file. * * @access public * * @return bool True if loaded, false if not. * */ function loadRenderObj($format, $rule) { $format = ucwords(strtolower($format)); $rule = ucwords(strtolower($rule)); $file = "$format/$rule.php"; $class = "Text_Wiki_Render_$format" . "_$rule"; if (! Typecho_Common::isAvailableClass($class)) { // load the class $loc = $this->findFile('render', $file); if ($loc) { // found the class include_once $loc; } else { // can't find the class return $this->error( "Render rule '$rule' in format '$format' not found" ); } } $this->renderObj[$rule] = new $class($this); } /** * * Load a format-render class file. * * @access public * * @return bool True if loaded, false if not. * */ function loadFormatObj($format) { $format = ucwords(strtolower($format)); $file = $format . '.php'; $class = "Text_Wiki_Render_$format"; if (! Typecho_Common::isAvailableClass($class)) { $loc = $this->findFile('render', $file); if ($loc) { // found the class include_once $loc; } else { // can't find the class return $this->error( "Rendering format class '$class' not found" ); } } $this->formatObj[$format] = new $class($this); } /** * * Add a path to a path array. * * @access public * * @param string $type The path-type to add (parse or render). * * @param string $dir The directory to add to the path-type. * * @return void * */ function addPath($type, $dir) { $dir = $this->fixPath($dir); if (! isset($this->path[$type])) { $this->path[$type] = array($dir); } else { array_unshift($this->path[$type], $dir); } } /** * * Get the current path array for a path-type. * * @access public * * @param string $type The path-type to look up (plugin, filter, or * template). If not set, returns all path types. * * @return array The array of paths for the requested type. * */ function getPath($type = null) { if (is_null($type)) { return $this->path; } elseif (! isset($this->path[$type])) { return array(); } else { return $this->path[$type]; } } /** * * Searches a series of paths for a given file. * * @param array $type The type of paths to search (template, plugin, * or filter). * * @param string $file The file name to look for. * * @return string|bool The full path and file name for the target file, * or boolean false if the file is not found in any of the paths. * */ function findFile($type, $file) { // get the set of paths $set = $this->getPath($type); // start looping through them foreach ($set as $path) { $fullname = $path . $this->_dirSep . $file; if (file_exists($fullname) && is_readable($fullname)) { return realpath($fullname); } } // could not find the file in the set of paths return false; } /** * * Append a trailing '/' to paths, unless the path is empty. * * @access private * * @param string $path The file path to fix * * @return string The fixed file path * */ function fixPath($path) { if (realpath($path)){ return realpath($path); // . (is_dir($path) ? $this->_dirSep : ''); } else { return ''; } /* $len = strlen($this->_dirSep); if (! empty($path) && substr($path, -1 * $len, $len) != $this->_dirSep) { return realpath($path) . $this->_dirSep; } else { return realpath($path); } */ } /** * * Simple error-object generator. * * @access public * * @param string $message The error message. * * @return object PEAR_Error * */ function &error($message) { /* if (! class_exists('PEAR_Error')) { include_once 'PEAR.php'; } */ throw new Exception($message); return false; //return PEAR::throwError($message); } /** * * Simple error checker. * * @access public * * @param mixed $obj Check if this is a PEAR_Error object or not. * * @return bool True if a PEAR_Error, false if not. * */ function isError(&$obj) { return is_a($obj, 'PEAR_Error'); } /** * Constructor: just adds the path to Creole rules * * @access public * @param array $rules The set of rules to load for this object. */ function checkInnerTags(&$text) { $started = array(); $i = false; while (($i = strpos($text, $this->delim, $i)) !== false) { $j = strpos($text, $this->delim, $i + 1); $t = substr($text, $i + 1, $j - $i - 1); $i = $j + 1; $rule = strtolower($this->tokens[$t][0]); $type = $this->tokens[$t][1]['type']; if ($type == 'start') { if (empty($started[$rule])) { $started[$rule] = 0; } $started[$rule] += 1; } else if ($type == 'end') { if (! $started[$rule]) return false; $started[$rule] -= 1; if (! $started[$rule]) unset($started[$rule]); } } return ! (count($started) > 0); } function restoreRaw($text) { $i = false; while (($i = strpos($text, $this->delim, $i)) !== false) { $j = strpos($text, $this->delim, $i + 1); $t = substr($text, $i + 1, $j - $i - 1); $rule = strtolower($this->tokens[$t][0]); if ($rule == 'raw') { $text = str_replace($this->delim. $t. $this->delim, $this->tokens[$t][1]['text'], $text); } else { $i = $j + 1; } } return $text; } } ?>
zzcode
trunk/Creole_Patch/Creole_Wiki.php
PHP
bsd
44,876
<?php // vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: /** * Preformatted rule end renderer for Xhtml * * PHP versions 4 and 5 * * @category Text * @package Text_Wiki * @author Paul M. Jones <pmjones@php.net> * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1 * @version CVS: $Id: Preformatted.php 182 2008-09-14 15:56:00Z i.feelinglucky $ * @link http://pear.php.net/package/Text_Wiki */ /** * This class renders preformated text in XHTML. * * @category Text * @package Text_Wiki * @author Paul M. Jones <pmjones@php.net> * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1 * @version Release: @package_version@ * @link http://pear.php.net/package/Text_Wiki */ class Text_Wiki_Render_Xhtml_Zzcode extends Text_Wiki_Render { /** * * Renders a token into text matching the requested format. * * @access public * * @param array $options The "options" portion of the token (second * element). * * @return string The text rendered from the token options. * */ function token($options) { if ($options['is_pre']){ $text = '<pre class="prettyprint">' . htmlspecialchars($options['content'], ENT_QUOTES) . '</pre>'; } else{ $text = htmlspecialchars($options['text'], ENT_QUOTES); } return $text; } } ?>
zzcode
trunk/Creole_Patch/Render/Xhtml/Zzcode.php
PHP
bsd
1,390
<?php /** * * Parses for preformatted text. * * @category Text * * @package Text_Wiki * * @author Tomaiuolo Michele <tomamic@yahoo.it> * * @license LGPL * * @version $Id: Preformatted.php 182 2008-09-14 15:56:00Z i.feelinglucky $ * */ class Text_Wiki_Parse_Zzcode extends Text_Wiki_Parse { /** * * The regular expression used to parse the source text and find * matches conforming to this rule. Used by the parse() method. * * @access public * * @var string * * @see parse() * */ var $regex = '/\[code\](.*?)\[\/code\]|<pre\sclass="prettyprint">(.*?)<\/pre>/is'; /** * * Generates a replacement for the matched text. Token options are: * * 'text' => The preformatted text. * * @access public * * @param array &$matches The array of matches from parse(). * * @return string A token to be used as a placeholder * in the source text for the preformatted text. * */ function process(&$matches) { $is_pre = false; $content = ''; if ( ! empty($matches[1])){ $is_pre = false; $content = $matches[1]; } elseif ( ! empty($matches[2])){ $is_pre = true; $content = $matches[2]; } $token = $this->wiki->addToken( $this->rule, array( 'text' => $matches[0], 'content' => $content, 'is_pre' => $is_pre ) ); return "\n\n" . $token . "\n\n"; } } ?>
zzcode
trunk/Creole_Patch/Parse/Zzcode.php
PHP
bsd
1,632
<?php /** * 代码高亮 * * @package ZzCode * @author John.H * @version 1.0.0 * @link http://typecho.org */ class ZzCode_Plugin implements Typecho_Plugin_Interface { public static function activate() { //Typecho_Plugin::factory('Widget_Abstract_Contents')->filter = array('Zzcode_Plugin', 'parse'); Typecho_Plugin::factory('Widget_Archive')->header = array('Zzcode_Plugin', 'header'); Typecho_Plugin::factory('Widget_Archive')->footer = array('Zzcode_Plugin', 'footer'); Typecho_Plugin::factory('Widget_Abstract_Contents')->excerpt = array('Zzcode_Plugin', 'parse'); Typecho_Plugin::factory('Widget_Abstract_Contents')->content = array('Zzcode_Plugin', 'parse'); } public static function deactivate(){} public static function config(Typecho_Widget_Helper_Form $form){} public static function personalConfig(Typecho_Widget_Helper_Form $form){} public static function header($header, $archive) { $href = '/usr/plugins/ZzCode/google-code-prettify/prettify.css'; echo '<link rel="stylesheet" type="text/css" media="all" href="' . $href . '" />'; } public static function footer($footer, $archive) { //$js_src = '/usr/plugins/ZzCode/google-code-prettify/prettify.js'; $js_src = 'http://www.gstatic.com/codesite/ph/17848733607936693291/js/prettify/prettify.js'; $prettify_js = " <script type=\"text/javascript\" src=\"{$js_src}\"></script> <script type=\"text/javascript\">if(prettyPrint)prettyPrint();</script> "; echo $prettify_js; } public static function parse($text, $widget, $lastResult) { $text = empty($lastResult) ? $text : $lastResult; $text = preg_replace('/(?:<pre>)?\[code\](.*?)\[\/code\](?:<\/pre>)?/is', '<pre class="prettyprint">$1</pre>', $text); return $text; } }
zzcode
trunk/Plugin.php
PHP
bsd
1,999
// Copyright (C) 2006 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview * some functions for browser-side pretty printing of code contained in html. * * The lexer should work on a number of languages including C and friends, * Java, Python, Bash, SQL, HTML, XML, CSS, Javascript, and Makefiles. * It works passably on Ruby, PHP and Awk and a decent subset of Perl, but, * because of commenting conventions, doesn't work on Smalltalk, Lisp-like, or * CAML-like languages. * * If there's a language not mentioned here, then I don't know it, and don't * know whether it works. If it has a C-like, Bash-like, or XML-like syntax * then it should work passably. * * Usage: * 1) include this source file in an html page via * <script type="text/javascript" src="/path/to/prettify.js"></script> * 2) define style rules. See the example page for examples. * 3) mark the <pre> and <code> tags in your source with class=prettyprint. * You can also use the (html deprecated) <xmp> tag, but the pretty printer * needs to do more substantial DOM manipulations to support that, so some * css styles may not be preserved. * That's it. I wanted to keep the API as simple as possible, so there's no * need to specify which language the code is in. * * Change log: * cbeust, 2006/08/22 * Java annotations (start with "@") are now captured as literals ("lit") */ // JSLint declarations /*global console, document, navigator, setTimeout, window */ /** * Split {@code prettyPrint} into multiple timeouts so as not to interfere with * UI events. * If set to {@code false}, {@code prettyPrint()} is synchronous. */ window['PR_SHOULD_USE_CONTINUATION'] = true; /** the number of characters between tab columns */ window['PR_TAB_WIDTH'] = 8; /** Walks the DOM returning a properly escaped version of innerHTML. * @param {Node} node * @param {Array.<string>} out output buffer that receives chunks of HTML. */ window['PR_normalizedHtml'] /** Contains functions for creating and registering new language handlers. * @type {Object} */ = window['PR'] /** Pretty print a chunk of code. * * @param {string} sourceCodeHtml code as html * @return {string} code as html, but prettier */ = window['prettyPrintOne'] /** Find all the {@code <pre>} and {@code <code>} tags in the DOM with * {@code class=prettyprint} and prettify them. * @param {Function?} opt_whenDone if specified, called when the last entry * has been finished. */ = window['prettyPrint'] = void 0; /** browser detection. @extern */ window['_pr_isIE6'] = function () { var isIE6 = navigator && navigator.userAgent && /\bMSIE 6\./.test(navigator.userAgent); window['_pr_isIE6'] = function () { return isIE6; }; return isIE6; }; (function () { // Keyword lists for various languages. var FLOW_CONTROL_KEYWORDS = "break continue do else for if return while "; var C_KEYWORDS = FLOW_CONTROL_KEYWORDS + "auto case char const default " + "double enum extern float goto int long register short signed sizeof " + "static struct switch typedef union unsigned void volatile "; var COMMON_KEYWORDS = C_KEYWORDS + "catch class delete false import " + "new operator private protected public this throw true try "; var CPP_KEYWORDS = COMMON_KEYWORDS + "alignof align_union asm axiom bool " + "concept concept_map const_cast constexpr decltype " + "dynamic_cast explicit export friend inline late_check " + "mutable namespace nullptr reinterpret_cast static_assert static_cast " + "template typeid typename typeof using virtual wchar_t where "; var JAVA_KEYWORDS = COMMON_KEYWORDS + "boolean byte extends final finally implements import instanceof null " + "native package strictfp super synchronized throws transient "; var CSHARP_KEYWORDS = JAVA_KEYWORDS + "as base by checked decimal delegate descending event " + "fixed foreach from group implicit in interface internal into is lock " + "object out override orderby params partial readonly ref sbyte sealed " + "stackalloc string select uint ulong unchecked unsafe ushort var "; var JSCRIPT_KEYWORDS = COMMON_KEYWORDS + "debugger eval export function get null set undefined var with " + "Infinity NaN "; var PERL_KEYWORDS = "caller delete die do dump elsif eval exit foreach for " + "goto if import last local my next no our print package redo require " + "sub undef unless until use wantarray while BEGIN END "; var PYTHON_KEYWORDS = FLOW_CONTROL_KEYWORDS + "and as assert class def del " + "elif except exec finally from global import in is lambda " + "nonlocal not or pass print raise try with yield " + "False True None "; var RUBY_KEYWORDS = FLOW_CONTROL_KEYWORDS + "alias and begin case class def" + " defined elsif end ensure false in module next nil not or redo rescue " + "retry self super then true undef unless until when yield BEGIN END "; var SH_KEYWORDS = FLOW_CONTROL_KEYWORDS + "case done elif esac eval fi " + "function in local set then until "; var ALL_KEYWORDS = ( CPP_KEYWORDS + CSHARP_KEYWORDS + JSCRIPT_KEYWORDS + PERL_KEYWORDS + PYTHON_KEYWORDS + RUBY_KEYWORDS + SH_KEYWORDS); // token style names. correspond to css classes /** token style for a string literal */ var PR_STRING = 'str'; /** token style for a keyword */ var PR_KEYWORD = 'kwd'; /** token style for a comment */ var PR_COMMENT = 'com'; /** token style for a type */ var PR_TYPE = 'typ'; /** token style for a literal value. e.g. 1, null, true. */ var PR_LITERAL = 'lit'; /** token style for a punctuation string. */ var PR_PUNCTUATION = 'pun'; /** token style for a punctuation string. */ var PR_PLAIN = 'pln'; /** token style for an sgml tag. */ var PR_TAG = 'tag'; /** token style for a markup declaration such as a DOCTYPE. */ var PR_DECLARATION = 'dec'; /** token style for embedded source. */ var PR_SOURCE = 'src'; /** token style for an sgml attribute name. */ var PR_ATTRIB_NAME = 'atn'; /** token style for an sgml attribute value. */ var PR_ATTRIB_VALUE = 'atv'; /** * A class that indicates a section of markup that is not code, e.g. to allow * embedding of line numbers within code listings. */ var PR_NOCODE = 'nocode'; /** A set of tokens that can precede a regular expression literal in * javascript. * http://www.mozilla.org/js/language/js20/rationale/syntax.html has the full * list, but I've removed ones that might be problematic when seen in * languages that don't support regular expression literals. * * <p>Specifically, I've removed any keywords that can't precede a regexp * literal in a syntactically legal javascript program, and I've removed the * "in" keyword since it's not a keyword in many languages, and might be used * as a count of inches. * * <p>The link a above does not accurately describe EcmaScript rules since * it fails to distinguish between (a=++/b/i) and (a++/b/i) but it works * very well in practice. * * @private */ var REGEXP_PRECEDER_PATTERN = function () { var preceders = [ "!", "!=", "!==", "#", "%", "%=", "&", "&&", "&&=", "&=", "(", "*", "*=", /* "+", */ "+=", ",", /* "-", */ "-=", "->", /*".", "..", "...", handled below */ "/", "/=", ":", "::", ";", "<", "<<", "<<=", "<=", "=", "==", "===", ">", ">=", ">>", ">>=", ">>>", ">>>=", "?", "@", "[", "^", "^=", "^^", "^^=", "{", "|", "|=", "||", "||=", "~" /* handles =~ and !~ */, "break", "case", "continue", "delete", "do", "else", "finally", "instanceof", "return", "throw", "try", "typeof" ]; var pattern = '(?:^^|[+-]'; for (var i = 0; i < preceders.length; ++i) { pattern += '|' + preceders[i].replace(/([^=<>:&a-z])/g, '\\$1'); } pattern += ')\\s*'; // matches at end, and matches empty string return pattern; // CAVEAT: this does not properly handle the case where a regular // expression immediately follows another since a regular expression may // have flags for case-sensitivity and the like. Having regexp tokens // adjacent is not valid in any language I'm aware of, so I'm punting. // TODO: maybe style special characters inside a regexp as punctuation. }(); // Define regexps here so that the interpreter doesn't have to create an // object each time the function containing them is called. // The language spec requires a new object created even if you don't access // the $1 members. var pr_amp = /&/g; var pr_lt = /</g; var pr_gt = />/g; var pr_quot = /\"/g; /** like textToHtml but escapes double quotes to be attribute safe. */ function attribToHtml(str) { return str.replace(pr_amp, '&amp;') .replace(pr_lt, '&lt;') .replace(pr_gt, '&gt;') .replace(pr_quot, '&quot;'); } /** escapest html special characters to html. */ function textToHtml(str) { return str.replace(pr_amp, '&amp;') .replace(pr_lt, '&lt;') .replace(pr_gt, '&gt;'); } var pr_ltEnt = /&lt;/g; var pr_gtEnt = /&gt;/g; var pr_aposEnt = /&apos;/g; var pr_quotEnt = /&quot;/g; var pr_ampEnt = /&amp;/g; var pr_nbspEnt = /&nbsp;/g; /** unescapes html to plain text. */ function htmlToText(html) { var pos = html.indexOf('&'); if (pos < 0) { return html; } // Handle numeric entities specially. We can't use functional substitution // since that doesn't work in older versions of Safari. // These should be rare since most browsers convert them to normal chars. for (--pos; (pos = html.indexOf('&#', pos + 1)) >= 0;) { var end = html.indexOf(';', pos); if (end >= 0) { var num = html.substring(pos + 3, end); var radix = 10; if (num && num.charAt(0) === 'x') { num = num.substring(1); radix = 16; } var codePoint = parseInt(num, radix); if (!isNaN(codePoint)) { html = (html.substring(0, pos) + String.fromCharCode(codePoint) + html.substring(end + 1)); } } } return html.replace(pr_ltEnt, '<') .replace(pr_gtEnt, '>') .replace(pr_aposEnt, "'") .replace(pr_quotEnt, '"') .replace(pr_ampEnt, '&') .replace(pr_nbspEnt, ' '); } /** is the given node's innerHTML normally unescaped? */ function isRawContent(node) { return 'XMP' === node.tagName; } function normalizedHtml(node, out) { switch (node.nodeType) { case 1: // an element var name = node.tagName.toLowerCase(); out.push('<', name); for (var i = 0; i < node.attributes.length; ++i) { var attr = node.attributes[i]; if (!attr.specified) { continue; } out.push(' '); normalizedHtml(attr, out); } out.push('>'); for (var child = node.firstChild; child; child = child.nextSibling) { normalizedHtml(child, out); } if (node.firstChild || !/^(?:br|link|img)$/.test(name)) { out.push('<\/', name, '>'); } break; case 2: // an attribute out.push(node.name.toLowerCase(), '="', attribToHtml(node.value), '"'); break; case 3: case 4: // text out.push(textToHtml(node.nodeValue)); break; } } /** * Given a group of {@link RegExp}s, returns a {@code RegExp} that globally * matches the union o the sets o strings matched d by the input RegExp. * Since it matches globally, if the input strings have a start-of-input * anchor (/^.../), it is ignored for the purposes of unioning. * @param {Array.<RegExpr>} regexs non multiline, non-global regexs. * @return {RegExp} a global regex. */ function combinePrefixPatterns(regexs) { var capturedGroupIndex = 0; var needToFoldCase = false; var ignoreCase = false; for (var i = 0, n = regexs.length; i < n; ++i) { var regex = regexs[i]; if (regex.ignoreCase) { ignoreCase = true; } else if (/[a-z]/i.test(regex.source.replace( /\\u[0-9a-f]{4}|\\x[0-9a-f]{2}|\\[^ux]/gi, ''))) { needToFoldCase = true; ignoreCase = false; break; } } function decodeEscape(charsetPart) { if (charsetPart.charAt(0) !== '\\') { return charsetPart.charCodeAt(0); } switch (charsetPart.charAt(1)) { case 'b': return 8; case 't': return 9; case 'n': return 0xa; case 'v': return 0xb; case 'f': return 0xc; case 'r': return 0xd; case 'u': case 'x': return parseInt(charsetPart.substring(2), 16) || charsetPart.charCodeAt(1); case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': return parseInt(charsetPart.substring(1), 8); default: return charsetPart.charCodeAt(1); } } function encodeEscape(charCode) { if (charCode < 0x20) { return (charCode < 0x10 ? '\\x0' : '\\x') + charCode.toString(16); } var ch = String.fromCharCode(charCode); if (ch === '\\' || ch === '-' || ch === '[' || ch === ']') { ch = '\\' + ch; } return ch; } function caseFoldCharset(charSet) { var charsetParts = charSet.substring(1, charSet.length - 1).match( new RegExp( '\\\\u[0-9A-Fa-f]{4}' + '|\\\\x[0-9A-Fa-f]{2}' + '|\\\\[0-3][0-7]{0,2}' + '|\\\\[0-7]{1,2}' + '|\\\\[\\s\\S]' + '|-' + '|[^-\\\\]', 'g')); var groups = []; var ranges = []; var inverse = charsetParts[0] === '^'; for (var i = inverse ? 1 : 0, n = charsetParts.length; i < n; ++i) { var p = charsetParts[i]; switch (p) { case '\\B': case '\\b': case '\\D': case '\\d': case '\\S': case '\\s': case '\\W': case '\\w': groups.push(p); continue; } var start = decodeEscape(p); var end; if (i + 2 < n && '-' === charsetParts[i + 1]) { end = decodeEscape(charsetParts[i + 2]); i += 2; } else { end = start; } ranges.push([start, end]); // If the range might intersect letters, then expand it. if (!(end < 65 || start > 122)) { if (!(end < 65 || start > 90)) { ranges.push([Math.max(65, start) | 32, Math.min(end, 90) | 32]); } if (!(end < 97 || start > 122)) { ranges.push([Math.max(97, start) & ~32, Math.min(end, 122) & ~32]); } } } // [[1, 10], [3, 4], [8, 12], [14, 14], [16, 16], [17, 17]] // -> [[1, 12], [14, 14], [16, 17]] ranges.sort(function (a, b) { return (a[0] - b[0]) || (b[1] - a[1]); }); var consolidatedRanges = []; var lastRange = [NaN, NaN]; for (var i = 0; i < ranges.length; ++i) { var range = ranges[i]; if (range[0] <= lastRange[1] + 1) { lastRange[1] = Math.max(lastRange[1], range[1]); } else { consolidatedRanges.push(lastRange = range); } } var out = ['[']; if (inverse) { out.push('^'); } out.push.apply(out, groups); for (var i = 0; i < consolidatedRanges.length; ++i) { var range = consolidatedRanges[i]; out.push(encodeEscape(range[0])); if (range[1] > range[0]) { if (range[1] + 1 > range[0]) { out.push('-'); } out.push(encodeEscape(range[1])); } } out.push(']'); return out.join(''); } function allowAnywhereFoldCaseAndRenumberGroups(regex) { // Split into character sets, escape sequences, punctuation strings // like ('(', '(?:', ')', '^'), and runs of characters that do not // include any of the above. var parts = regex.source.match( new RegExp( '(?:' + '\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]' // a character set + '|\\\\u[A-Fa-f0-9]{4}' // a unicode escape + '|\\\\x[A-Fa-f0-9]{2}' // a hex escape + '|\\\\[0-9]+' // a back-reference or octal escape + '|\\\\[^ux0-9]' // other escape sequence + '|\\(\\?[:!=]' // start of a non-capturing group + '|[\\(\\)\\^]' // start/emd of a group, or line start + '|[^\\x5B\\x5C\\(\\)\\^]+' // run of other characters + ')', 'g')); var n = parts.length; // Maps captured group numbers to the number they will occupy in // the output or to -1 if that has not been determined, or to // undefined if they need not be capturing in the output. var capturedGroups = []; // Walk over and identify back references to build the capturedGroups // mapping. var groupIndex; for (var i = 0, groupIndex = 0; i < n; ++i) { var p = parts[i]; if (p === '(') { // groups are 1-indexed, so max group index is count of '(' ++groupIndex; } else if ('\\' === p.charAt(0)) { var decimalValue = +p.substring(1); if (decimalValue && decimalValue <= groupIndex) { capturedGroups[decimalValue] = -1; } } } // Renumber groups and reduce capturing groups to non-capturing groups // where possible. for (var i = 1; i < capturedGroups.length; ++i) { if (-1 === capturedGroups[i]) { capturedGroups[i] = ++capturedGroupIndex; } } for (var i = 0, groupIndex = 0; i < n; ++i) { var p = parts[i]; if (p === '(') { ++groupIndex; if (capturedGroups[groupIndex] === undefined) { parts[i] = '(?:'; } } else if ('\\' === p.charAt(0)) { var decimalValue = +p.substring(1); if (decimalValue && decimalValue <= groupIndex) { parts[i] = '\\' + capturedGroups[groupIndex]; } } } // Remove any prefix anchors so that the output will match anywhere. // ^^ really does mean an anchored match though. for (var i = 0, groupIndex = 0; i < n; ++i) { if ('^' === parts[i] && '^' !== parts[i + 1]) { parts[i] = ''; } } // Expand letters to groupts to handle mixing of case-sensitive and // case-insensitive patterns if necessary. if (regex.ignoreCase && needToFoldCase) { for (var i = 0; i < n; ++i) { var p = parts[i]; var ch0 = p.charAt(0); if (p.length >= 2 && ch0 === '[') { parts[i] = caseFoldCharset(p); } else if (ch0 !== '\\') { // TODO: handle letters in numeric escapes. parts[i] = p.replace( /[a-zA-Z]/g, function (ch) { var cc = ch.charCodeAt(0); return '[' + String.fromCharCode(cc & ~32, cc | 32) + ']'; }); } } } return parts.join(''); } var rewritten = []; for (var i = 0, n = regexs.length; i < n; ++i) { var regex = regexs[i]; if (regex.global || regex.multiline) { throw new Error('' + regex); } rewritten.push( '(?:' + allowAnywhereFoldCaseAndRenumberGroups(regex) + ')'); } return new RegExp(rewritten.join('|'), ignoreCase ? 'gi' : 'g'); } var PR_innerHtmlWorks = null; function getInnerHtml(node) { // inner html is hopelessly broken in Safari 2.0.4 when the content is // an html description of well formed XML and the containing tag is a PRE // tag, so we detect that case and emulate innerHTML. if (null === PR_innerHtmlWorks) { var testNode = document.createElement('PRE'); testNode.appendChild( document.createTextNode('<!DOCTYPE foo PUBLIC "foo bar">\n<foo />')); PR_innerHtmlWorks = !/</.test(testNode.innerHTML); } if (PR_innerHtmlWorks) { var content = node.innerHTML; // XMP tags contain unescaped entities so require special handling. if (isRawContent(node)) { content = textToHtml(content); } return content; } var out = []; for (var child = node.firstChild; child; child = child.nextSibling) { normalizedHtml(child, out); } return out.join(''); } /** returns a function that expand tabs to spaces. This function can be fed * successive chunks of text, and will maintain its own internal state to * keep track of how tabs are expanded. * @return {function (string) : string} a function that takes * plain text and return the text with tabs expanded. * @private */ function makeTabExpander(tabWidth) { var SPACES = ' '; var charInLine = 0; return function (plainText) { // walk over each character looking for tabs and newlines. // On tabs, expand them. On newlines, reset charInLine. // Otherwise increment charInLine var out = null; var pos = 0; for (var i = 0, n = plainText.length; i < n; ++i) { var ch = plainText.charAt(i); switch (ch) { case '\t': if (!out) { out = []; } out.push(plainText.substring(pos, i)); // calculate how much space we need in front of this part // nSpaces is the amount of padding -- the number of spaces needed // to move us to the next column, where columns occur at factors of // tabWidth. var nSpaces = tabWidth - (charInLine % tabWidth); charInLine += nSpaces; for (; nSpaces >= 0; nSpaces -= SPACES.length) { out.push(SPACES.substring(0, nSpaces)); } pos = i + 1; break; case '\n': charInLine = 0; break; default: ++charInLine; } } if (!out) { return plainText; } out.push(plainText.substring(pos)); return out.join(''); }; } var pr_chunkPattern = new RegExp( '[^<]+' // A run of characters other than '<' + '|<\!--[\\s\\S]*?--\>' // an HTML comment + '|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>' // a CDATA section + '|</?[a-zA-Z][^>]*>' // a probable tag that should not be highlighted + '|<', // A '<' that does not begin a larger chunk 'g'); var pr_commentPrefix = /^<\!--/; var pr_cdataPrefix = /^<\[CDATA\[/; var pr_brPrefix = /^<br\b/i; var pr_tagNameRe = /^<(\/?)([a-zA-Z]+)/; /** split markup into chunks of html tags (style null) and * plain text (style {@link #PR_PLAIN}), converting tags which are * significant for tokenization (<br>) into their textual equivalent. * * @param {string} s html where whitespace is considered significant. * @return {Object} source code and extracted tags. * @private */ function extractTags(s) { // since the pattern has the 'g' modifier and defines no capturing groups, // this will return a list of all chunks which we then classify and wrap as // PR_Tokens var matches = s.match(pr_chunkPattern); var sourceBuf = []; var sourceBufLen = 0; var extractedTags = []; if (matches) { for (var i = 0, n = matches.length; i < n; ++i) { var match = matches[i]; if (match.length > 1 && match.charAt(0) === '<') { if (pr_commentPrefix.test(match)) { continue; } if (pr_cdataPrefix.test(match)) { // strip CDATA prefix and suffix. Don't unescape since it's CDATA sourceBuf.push(match.substring(9, match.length - 3)); sourceBufLen += match.length - 12; } else if (pr_brPrefix.test(match)) { // <br> tags are lexically significant so convert them to text. // This is undone later. sourceBuf.push('\n'); ++sourceBufLen; } else { if (match.indexOf(PR_NOCODE) >= 0 && isNoCodeTag(match)) { // A <span class="nocode"> will start a section that should be // ignored. Continue walking the list until we see a matching end // tag. var name = match.match(pr_tagNameRe)[2]; var depth = 1; var j; end_tag_loop: for (j = i + 1; j < n; ++j) { var name2 = matches[j].match(pr_tagNameRe); if (name2 && name2[2] === name) { if (name2[1] === '/') { if (--depth === 0) { break end_tag_loop; } } else { ++depth; } } } if (j < n) { extractedTags.push( sourceBufLen, matches.slice(i, j + 1).join('')); i = j; } else { // Ignore unclosed sections. extractedTags.push(sourceBufLen, match); } } else { extractedTags.push(sourceBufLen, match); } } } else { var literalText = htmlToText(match); sourceBuf.push(literalText); sourceBufLen += literalText.length; } } } return { source: sourceBuf.join(''), tags: extractedTags }; } /** True if the given tag contains a class attribute with the nocode class. */ function isNoCodeTag(tag) { return !!tag // First canonicalize the representation of attributes .replace(/\s(\w+)\s*=\s*(?:\"([^\"]*)\"|'([^\']*)'|(\S+))/g, ' $1="$2$3$4"') // Then look for the attribute we want. .match(/[cC][lL][aA][sS][sS]=\"[^\"]*\bnocode\b/); } /** * Apply the given language handler to sourceCode and add the resulting * decorations to out. * @param {number} basePos the index of sourceCode within the chunk of source * whose decorations are already present on out. */ function appendDecorations(basePos, sourceCode, langHandler, out) { if (!sourceCode) { return; } var job = { source: sourceCode, basePos: basePos }; langHandler(job); out.push.apply(out, job.decorations); } /** Given triples of [style, pattern, context] returns a lexing function, * The lexing function interprets the patterns to find token boundaries and * returns a decoration list of the form * [index_0, style_0, index_1, style_1, ..., index_n, style_n] * where index_n is an index into the sourceCode, and style_n is a style * constant like PR_PLAIN. index_n-1 <= index_n, and style_n-1 applies to * all characters in sourceCode[index_n-1:index_n]. * * The stylePatterns is a list whose elements have the form * [style : string, pattern : RegExp, DEPRECATED, shortcut : string]. * * Style is a style constant like PR_PLAIN, or can be a string of the * form 'lang-FOO', where FOO is a language extension describing the * language of the portion of the token in $1 after pattern executes. * E.g., if style is 'lang-lisp', and group 1 contains the text * '(hello (world))', then that portion of the token will be passed to the * registered lisp handler for formatting. * The text before and after group 1 will be restyled using this decorator * so decorators should take care that this doesn't result in infinite * recursion. For example, the HTML lexer rule for SCRIPT elements looks * something like ['lang-js', /<[s]cript>(.+?)<\/script>/]. This may match * '<script>foo()<\/script>', which would cause the current decorator to * be called with '<script>' which would not match the same rule since * group 1 must not be empty, so it would be instead styled as PR_TAG by * the generic tag rule. The handler registered for the 'js' extension would * then be called with 'foo()', and finally, the current decorator would * be called with '<\/script>' which would not match the original rule and * so the generic tag rule would identify it as a tag. * * Pattern must only match prefixes, and if it matches a prefix, then that * match is considered a token with the same style. * * Context is applied to the last non-whitespace, non-comment token * recognized. * * Shortcut is an optional string of characters, any of which, if the first * character, gurantee that this pattern and only this pattern matches. * * @param {Array} shortcutStylePatterns patterns that always start with * a known character. Must have a shortcut string. * @param {Array} fallthroughStylePatterns patterns that will be tried in * order if the shortcut ones fail. May have shortcuts. * * @return {function (Object)} a * function that takes source code and returns a list of decorations. */ function createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns) { var shortcuts = {}; var tokenizer; (function () { var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns); var allRegexs = []; var regexKeys = {}; for (var i = 0, n = allPatterns.length; i < n; ++i) { var patternParts = allPatterns[i]; var shortcutChars = patternParts[3]; if (shortcutChars) { for (var c = shortcutChars.length; --c >= 0;) { shortcuts[shortcutChars.charAt(c)] = patternParts; } } var regex = patternParts[1]; var k = '' + regex; if (!regexKeys.hasOwnProperty(k)) { allRegexs.push(regex); regexKeys[k] = null; } } allRegexs.push(/[\0-\uffff]/); tokenizer = combinePrefixPatterns(allRegexs); })(); var nPatterns = fallthroughStylePatterns.length; var notWs = /\S/; /** * Lexes job.source and produces an output array job.decorations of style * classes preceded by the position at which they start in job.source in * order. * * @param {Object} job an object like {@code * source: {string} sourceText plain text, * basePos: {int} position of job.source in the larger chunk of * sourceCode. * } */ var decorate = function (job) { var sourceCode = job.source, basePos = job.basePos; /** Even entries are positions in source in ascending order. Odd enties * are style markers (e.g., PR_COMMENT) that run from that position until * the end. * @type {Array.<number|string>} */ var decorations = [basePos, PR_PLAIN]; var pos = 0; // index into sourceCode var tokens = sourceCode.match(tokenizer) || []; var styleCache = {}; for (var ti = 0, nTokens = tokens.length; ti < nTokens; ++ti) { var token = tokens[ti]; var style = styleCache[token]; var match; var isEmbedded; if (typeof style === 'string') { isEmbedded = false; } else { var patternParts = shortcuts[token.charAt(0)]; if (patternParts) { match = token.match(patternParts[1]); style = patternParts[0]; } else { for (var i = 0; i < nPatterns; ++i) { patternParts = fallthroughStylePatterns[i]; match = token.match(patternParts[1]); if (match) { style = patternParts[0]; break; } } if (!match) { // make sure that we make progress style = PR_PLAIN; } } isEmbedded = style.length >= 5 && 'lang-' === style.substring(0, 5); if (isEmbedded && !(match && match[1])) { isEmbedded = false; style = PR_SOURCE; } if (!isEmbedded) { styleCache[token] = style; } } var tokenStart = pos; pos += token.length; if (!isEmbedded) { decorations.push(basePos + tokenStart, style); } else { // Treat group 1 as an embedded block of source code. var embeddedSource = match[1]; var embeddedSourceStart = token.indexOf(embeddedSource); var embeddedSourceEnd = embeddedSourceStart + embeddedSource.length; var lang = style.substring(5); var size = decorations.length - 10; // Decorate the left of the embedded source appendDecorations( basePos + tokenStart, token.substring(0, embeddedSourceStart), decorate, decorations); // Decorate the embedded source appendDecorations( basePos + tokenStart + embeddedSourceStart, embeddedSource, langHandlerForExtension(lang, embeddedSource), decorations); // Decorate the right of the embedded section appendDecorations( basePos + tokenStart + embeddedSourceEnd, token.substring(embeddedSourceEnd), decorate, decorations); } } job.decorations = decorations; }; return decorate; } /** returns a function that produces a list of decorations from source text. * * This code treats ", ', and ` as string delimiters, and \ as a string * escape. It does not recognize perl's qq() style strings. * It has no special handling for double delimiter escapes as in basic, or * the tripled delimiters used in python, but should work on those regardless * although in those cases a single string literal may be broken up into * multiple adjacent string literals. * * It recognizes C, C++, and shell style comments. * * @param {Object} options a set of optional parameters. * @return {function (Object)} a function that examines the source code * in the input job and builds the decoration list. */ function sourceDecorator(options) { var shortcutStylePatterns = [], fallthroughStylePatterns = []; if (options['tripleQuotedStrings']) { // '''multi-line-string''', 'single-line-string', and double-quoted shortcutStylePatterns.push( [PR_STRING, /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/, null, '\'"']); } else if (options['multiLineStrings']) { // 'multi-line-string', "multi-line-string" shortcutStylePatterns.push( [PR_STRING, /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/, null, '\'"`']); } else { // 'single-line-string', "single-line-string" shortcutStylePatterns.push( [PR_STRING, /^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/, null, '"\'']); } if (options['hashComments']) { if (options['cStyleComments']) { // Stop C preprocessor declarations at an unclosed open comment shortcutStylePatterns.push( [PR_COMMENT, /^#(?:[^\r\n\/]|\/(?!\*)|\/\*[^\r\n]*?\*\/)*/, null, '#']); } else { shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']); } } if (options['cStyleComments']) { fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]); fallthroughStylePatterns.push( [PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]); } if (options['regexLiterals']) { var REGEX_LITERAL = ( // A regular expression literal starts with a slash that is // not followed by * or / so that it is not confused with // comments. '/(?=[^/*])' // and then contains any number of raw characters, + '(?:[^/\\x5B\\x5C]' // escape sequences (\x5C), + '|\\x5C[\\s\\S]' // or non-nesting character sets (\x5B\x5D); + '|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+' // finally closed by a /. + '/'); fallthroughStylePatterns.push( ['lang-regex', new RegExp('^' + REGEXP_PRECEDER_PATTERN + '(' + REGEX_LITERAL + ')') ]); } var keywords = options['keywords'].replace(/^\s+|\s+$/g, ''); if (keywords.length) { fallthroughStylePatterns.push( [PR_KEYWORD, new RegExp('^(?:' + keywords.replace(/\s+/g, '|') + ')\\b'), null]); } shortcutStylePatterns.push([PR_PLAIN, /^\s+/, null, ' \r\n\t\xA0']); fallthroughStylePatterns.push( // TODO(mikesamuel): recognize non-latin letters and numerals in idents [PR_LITERAL, /^@[a-z_$][a-z_$@0-9]*/i, null, '@'], [PR_TYPE, /^@?[A-Z]+[a-z][A-Za-z_$@0-9]*/, null], [PR_PLAIN, /^[a-z_$][a-z_$@0-9]*/i, null], [PR_LITERAL, new RegExp( '^(?:' // A hex number + '0x[a-f0-9]+' // or an octal or decimal number, + '|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)' // possibly in scientific notation + '(?:e[+\\-]?\\d+)?' + ')' // with an optional modifier like UL for unsigned long + '[a-z]*', 'i'), null, '0123456789'], [PR_PUNCTUATION, /^.[^\s\w\.$@\'\"\`\/\#]*/, null]); return createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns); } var decorateSource = sourceDecorator({ 'keywords': ALL_KEYWORDS, 'hashComments': true, 'cStyleComments': true, 'multiLineStrings': true, 'regexLiterals': true }); /** Breaks {@code job.source} around style boundaries in * {@code job.decorations} while re-interleaving {@code job.extractedTags}, * and leaves the result in {@code job.prettyPrintedHtml}. * @param {Object} job like { * source: {string} source as plain text, * extractedTags: {Array.<number|string>} extractedTags chunks of raw * html preceded by their position in {@code job.source} * in order * decorations: {Array.<number|string} an array of style classes preceded * by the position at which they start in job.source in order * } * @private */ function recombineTagsAndDecorations(job) { var sourceText = job.source; var extractedTags = job.extractedTags; var decorations = job.decorations; var html = []; // index past the last char in sourceText written to html var outputIdx = 0; var openDecoration = null; var currentDecoration = null; var tagPos = 0; // index into extractedTags var decPos = 0; // index into decorations var tabExpander = makeTabExpander(window['PR_TAB_WIDTH']); var adjacentSpaceRe = /([\r\n ]) /g; var startOrSpaceRe = /(^| ) /gm; var newlineRe = /\r\n?|\n/g; var trailingSpaceRe = /[ \r\n]$/; var lastWasSpace = true; // the last text chunk emitted ended with a space. // A helper function that is responsible for opening sections of decoration // and outputing properly escaped chunks of source function emitTextUpTo(sourceIdx) { if (sourceIdx > outputIdx) { if (openDecoration && openDecoration !== currentDecoration) { // Close the current decoration html.push('</span>'); openDecoration = null; } if (!openDecoration && currentDecoration) { openDecoration = currentDecoration; html.push('<span class="', openDecoration, '">'); } // This interacts badly with some wikis which introduces paragraph tags // into pre blocks for some strange reason. // It's necessary for IE though which seems to lose the preformattedness // of <pre> tags when their innerHTML is assigned. // http://stud3.tuwien.ac.at/~e0226430/innerHtmlQuirk.html // and it serves to undo the conversion of <br>s to newlines done in // chunkify. var htmlChunk = textToHtml( tabExpander(sourceText.substring(outputIdx, sourceIdx))) .replace(lastWasSpace ? startOrSpaceRe : adjacentSpaceRe, '$1&nbsp;'); // Keep track of whether we need to escape space at the beginning of the // next chunk. lastWasSpace = trailingSpaceRe.test(htmlChunk); // IE collapses multiple adjacient <br>s into 1 line break. // Prefix every <br> with '&nbsp;' can prevent such IE's behavior. var lineBreakHtml = window['_pr_isIE6']() ? '&nbsp;<br />' : '<br />'; html.push(htmlChunk.replace(newlineRe, lineBreakHtml)); outputIdx = sourceIdx; } } while (true) { // Determine if we're going to consume a tag this time around. Otherwise // we consume a decoration or exit. var outputTag; if (tagPos < extractedTags.length) { if (decPos < decorations.length) { // Pick one giving preference to extractedTags since we shouldn't open // a new style that we're going to have to immediately close in order // to output a tag. outputTag = extractedTags[tagPos] <= decorations[decPos]; } else { outputTag = true; } } else { outputTag = false; } // Consume either a decoration or a tag or exit. if (outputTag) { emitTextUpTo(extractedTags[tagPos]); if (openDecoration) { // Close the current decoration html.push('</span>'); openDecoration = null; } html.push(extractedTags[tagPos + 1]); tagPos += 2; } else if (decPos < decorations.length) { emitTextUpTo(decorations[decPos]); currentDecoration = decorations[decPos + 1]; decPos += 2; } else { break; } } emitTextUpTo(sourceText.length); if (openDecoration) { html.push('</span>'); } job.prettyPrintedHtml = html.join(''); } /** Maps language-specific file extensions to handlers. */ var langHandlerRegistry = {}; /** Register a language handler for the given file extensions. * @param {function (Object)} handler a function from source code to a list * of decorations. Takes a single argument job which describes the * state of the computation. The single parameter has the form * {@code { * source: {string} as plain text. * decorations: {Array.<number|string>} an array of style classes * preceded by the position at which they start in * job.source in order. * The language handler should assigned this field. * basePos: {int} the position of source in the larger source chunk. * All positions in the output decorations array are relative * to the larger source chunk. * } } * @param {Array.<string>} fileExtensions */ function registerLangHandler(handler, fileExtensions) { for (var i = fileExtensions.length; --i >= 0;) { var ext = fileExtensions[i]; if (!langHandlerRegistry.hasOwnProperty(ext)) { langHandlerRegistry[ext] = handler; } else if ('console' in window) { console.warn('cannot override language handler %s', ext); } } } function langHandlerForExtension(extension, source) { if (!(extension && langHandlerRegistry.hasOwnProperty(extension))) { // Treat it as markup if the first non whitespace character is a < and // the last non-whitespace character is a >. extension = /^\s*</.test(source) ? 'default-markup' : 'default-code'; } return langHandlerRegistry[extension]; } registerLangHandler(decorateSource, ['default-code']); registerLangHandler( createSimpleLexer( [], [ [PR_PLAIN, /^[^<?]+/], [PR_DECLARATION, /^<!\w[^>]*(?:>|$)/], [PR_COMMENT, /^<\!--[\s\S]*?(?:-\->|$)/], // Unescaped content in an unknown language ['lang-', /^<\?([\s\S]+?)(?:\?>|$)/], ['lang-', /^<%([\s\S]+?)(?:%>|$)/], [PR_PUNCTUATION, /^(?:<[%?]|[%?]>)/], ['lang-', /^<xmp\b[^>]*>([\s\S]+?)<\/xmp\b[^>]*>/i], // Unescaped content in javascript. (Or possibly vbscript). ['lang-js', /^<script\b[^>]*>([\s\S]+?)<\/script\b[^>]*>/i], // Contains unescaped stylesheet content ['lang-css', /^<style\b[^>]*>([\s\S]+?)<\/style\b[^>]*>/i], ['lang-in.tag', /^(<\/?[a-z][^<>]*>)/i] ]), ['default-markup', 'htm', 'html', 'mxml', 'xhtml', 'xml', 'xsl']); registerLangHandler( createSimpleLexer( [ [PR_PLAIN, /^[\s]+/, null, ' \t\r\n'], [PR_ATTRIB_VALUE, /^(?:\"[^\"]*\"?|\'[^\']*\'?)/, null, '\"\''] ], [ [PR_TAG, /^^<\/?[a-z](?:[\w:-]*\w)?|\/?>$/], [PR_ATTRIB_NAME, /^(?!style\b|on)[a-z](?:[\w:-]*\w)?/], ['lang-uq.val', /^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/], [PR_PUNCTUATION, /^[=<>\/]+/], ['lang-js', /^on\w+\s*=\s*\"([^\"]+)\"/i], ['lang-js', /^on\w+\s*=\s*\'([^\']+)\'/i], ['lang-js', /^on\w+\s*=\s*([^\"\'>\s]+)/i], ['lang-css', /^sty\w+\s*=\s*\"([^\"]+)\"/i], ['lang-css', /^sty\w+\s*=\s*\'([^\']+)\'/i], ['lang-css', /^sty\w+\s*=\s*([^\"\'>\s]+)/i] ]), ['in.tag']); registerLangHandler( createSimpleLexer([], [[PR_ATTRIB_VALUE, /^[\s\S]+/]]), ['uq.val']); registerLangHandler(sourceDecorator({ 'keywords': CPP_KEYWORDS, 'hashComments': true, 'cStyleComments': true }), ['c', 'cc', 'cpp', 'cxx', 'cyc', 'm']); registerLangHandler(sourceDecorator({ 'keywords': 'null true false' }), ['json']); registerLangHandler(sourceDecorator({ 'keywords': CSHARP_KEYWORDS, 'hashComments': true, 'cStyleComments': true }), ['cs']); registerLangHandler(sourceDecorator({ 'keywords': JAVA_KEYWORDS, 'cStyleComments': true }), ['java']); registerLangHandler(sourceDecorator({ 'keywords': SH_KEYWORDS, 'hashComments': true, 'multiLineStrings': true }), ['bsh', 'csh', 'sh']); registerLangHandler(sourceDecorator({ 'keywords': PYTHON_KEYWORDS, 'hashComments': true, 'multiLineStrings': true, 'tripleQuotedStrings': true }), ['cv', 'py']); registerLangHandler(sourceDecorator({ 'keywords': PERL_KEYWORDS, 'hashComments': true, 'multiLineStrings': true, 'regexLiterals': true }), ['perl', 'pl', 'pm']); registerLangHandler(sourceDecorator({ 'keywords': RUBY_KEYWORDS, 'hashComments': true, 'multiLineStrings': true, 'regexLiterals': true }), ['rb']); registerLangHandler(sourceDecorator({ 'keywords': JSCRIPT_KEYWORDS, 'cStyleComments': true, 'regexLiterals': true }), ['js']); registerLangHandler( createSimpleLexer([], [[PR_STRING, /^[\s\S]+/]]), ['regex']); function applyDecorator(job) { var sourceCodeHtml = job.sourceCodeHtml; var opt_langExtension = job.langExtension; // Prepopulate output in case processing fails with an exception. job.prettyPrintedHtml = sourceCodeHtml; try { // Extract tags, and convert the source code to plain text. var sourceAndExtractedTags = extractTags(sourceCodeHtml); /** Plain text. @type {string} */ var source = sourceAndExtractedTags.source; job.source = source; job.basePos = 0; /** Even entries are positions in source in ascending order. Odd entries * are tags that were extracted at that position. * @type {Array.<number|string>} */ job.extractedTags = sourceAndExtractedTags.tags; // Apply the appropriate language handler langHandlerForExtension(opt_langExtension, source)(job); // Integrate the decorations and tags back into the source code to produce // a decorated html string which is left in job.prettyPrintedHtml. recombineTagsAndDecorations(job); } catch (e) { if ('console' in window) { console.log(e); console.trace(); } } } function prettyPrintOne(sourceCodeHtml, opt_langExtension) { var job = { sourceCodeHtml: sourceCodeHtml, langExtension: opt_langExtension }; applyDecorator(job); return job.prettyPrintedHtml; } function prettyPrint(opt_whenDone) { var isIE6 = window['_pr_isIE6'](); // fetch a list of nodes to rewrite var codeSegments = [ document.getElementsByTagName('pre'), document.getElementsByTagName('code'), document.getElementsByTagName('xmp') ]; var elements = []; for (var i = 0; i < codeSegments.length; ++i) { for (var j = 0, n = codeSegments[i].length; j < n; ++j) { elements.push(codeSegments[i][j]); } } codeSegments = null; var clock = Date; if (!clock['now']) { clock = { 'now': function () { return (new Date).getTime(); } }; } // The loop is broken into a series of continuations to make sure that we // don't make the browser unresponsive when rewriting a large page. var k = 0; var prettyPrintingJob; function doWork() { var endTime = (window['PR_SHOULD_USE_CONTINUATION'] ? clock.now() + 250 /* ms */ : Infinity); for (; k < elements.length && clock.now() < endTime; k++) { var cs = elements[k]; if (cs.className && cs.className.indexOf('prettyprint') >= 0) { // If the classes includes a language extensions, use it. // Language extensions can be specified like // <pre class="prettyprint lang-cpp"> // the language extension "cpp" is used to find a language handler as // passed to PR_registerLangHandler. var langExtension = cs.className.match(/\blang-(\w+)\b/); if (langExtension) { langExtension = langExtension[1]; } // make sure this is not nested in an already prettified element var nested = false; for (var p = cs.parentNode; p; p = p.parentNode) { if ((p.tagName === 'pre' || p.tagName === 'code' || p.tagName === 'xmp') && p.className && p.className.indexOf('prettyprint') >= 0) { nested = true; break; } } if (!nested) { // fetch the content as a snippet of properly escaped HTML. // Firefox adds newlines at the end. var content = getInnerHtml(cs); content = content.replace(/(?:\r\n?|\n)$/, ''); // do the pretty printing prettyPrintingJob = { sourceCodeHtml: content, langExtension: langExtension, sourceNode: cs }; applyDecorator(prettyPrintingJob); replaceWithPrettyPrintedHtml(); } } } if (k < elements.length) { // finish up in a continuation setTimeout(doWork, 250); } else if (opt_whenDone) { opt_whenDone(); } } function replaceWithPrettyPrintedHtml() { var newContent = prettyPrintingJob.prettyPrintedHtml; if (!newContent) { return; } var cs = prettyPrintingJob.sourceNode; // push the prettified html back into the tag. if (!isRawContent(cs)) { // just replace the old html with the new cs.innerHTML = newContent; } else { // we need to change the tag to a <pre> since <xmp>s do not allow // embedded tags such as the span tags used to attach styles to // sections of source code. var pre = document.createElement('PRE'); for (var i = 0; i < cs.attributes.length; ++i) { var a = cs.attributes[i]; if (a.specified) { var aname = a.name.toLowerCase(); if (aname === 'class') { pre.className = a.value; // For IE 6 } else { pre.setAttribute(a.name, a.value); } } } pre.innerHTML = newContent; // remove the old cs.parentNode.replaceChild(pre, cs); cs = pre; } // Replace <br>s with line-feeds so that copying and pasting works // on IE 6. // Doing this on other browsers breaks lots of stuff since \r\n is // treated as two newlines on Firefox, and doing this also slows // down rendering. if (isIE6 && cs.tagName === 'PRE') { var lineBreaks = cs.getElementsByTagName('br'); for (var j = lineBreaks.length; --j >= 0;) { var lineBreak = lineBreaks[j]; lineBreak.parentNode.replaceChild( document.createTextNode('\r'), lineBreak); } } } doWork(); } window['PR_normalizedHtml'] = normalizedHtml; window['prettyPrintOne'] = prettyPrintOne; window['prettyPrint'] = prettyPrint; window['PR'] = { 'combinePrefixPatterns': combinePrefixPatterns, 'createSimpleLexer': createSimpleLexer, 'registerLangHandler': registerLangHandler, 'sourceDecorator': sourceDecorator, 'PR_ATTRIB_NAME': PR_ATTRIB_NAME, 'PR_ATTRIB_VALUE': PR_ATTRIB_VALUE, 'PR_COMMENT': PR_COMMENT, 'PR_DECLARATION': PR_DECLARATION, 'PR_KEYWORD': PR_KEYWORD, 'PR_LITERAL': PR_LITERAL, 'PR_NOCODE': PR_NOCODE, 'PR_PLAIN': PR_PLAIN, 'PR_PUNCTUATION': PR_PUNCTUATION, 'PR_SOURCE': PR_SOURCE, 'PR_STRING': PR_STRING, 'PR_TAG': PR_TAG, 'PR_TYPE': PR_TYPE }; })();
zzcode
trunk/google-code-prettify/prettify.js
JavaScript
bsd
54,951
// Copyright (C) 2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview * Registers a language handler for various flavors of basic. * * * To use, include prettify.js and this file in your HTML page. * Then put your code in an HTML tag like * <pre class="prettyprint lang-vb"></pre> * * * http://msdn.microsoft.com/en-us/library/aa711638(VS.71).aspx defines the * visual basic grammar lexical grammar. * * @author mikesamuel@gmail.com */ PR.registerLangHandler( PR.createSimpleLexer( [ // Whitespace [PR.PR_PLAIN, /^[\t\n\r \xA0\u2028\u2029]+/, null, '\t\n\r \xA0\u2028\u2029'], // A double quoted string with quotes escaped by doubling them. // A single character can be suffixed with C. [PR.PR_STRING, /^(?:[\"\u201C\u201D](?:[^\"\u201C\u201D]|[\"\u201C\u201D]{2})(?:[\"\u201C\u201D]c|$)|[\"\u201C\u201D](?:[^\"\u201C\u201D]|[\"\u201C\u201D]{2})*(?:[\"\u201C\u201D]|$))/i, null, '"\u201C\u201D'], // A comment starts with a single quote and runs until the end of the // line. [PR.PR_COMMENT, /^[\'\u2018\u2019][^\r\n\u2028\u2029]*/, null, '\'\u2018\u2019'] ], [ [PR.PR_KEYWORD, /^(?:AddHandler|AddressOf|Alias|And|AndAlso|Ansi|As|Assembly|Auto|Boolean|ByRef|Byte|ByVal|Call|Case|Catch|CBool|CByte|CChar|CDate|CDbl|CDec|Char|CInt|Class|CLng|CObj|Const|CShort|CSng|CStr|CType|Date|Decimal|Declare|Default|Delegate|Dim|DirectCast|Do|Double|Each|Else|ElseIf|End|EndIf|Enum|Erase|Error|Event|Exit|Finally|For|Friend|Function|Get|GetType|GoSub|GoTo|Handles|If|Implements|Imports|In|Inherits|Integer|Interface|Is|Let|Lib|Like|Long|Loop|Me|Mod|Module|MustInherit|MustOverride|MyBase|MyClass|Namespace|New|Next|Not|NotInheritable|NotOverridable|Object|On|Option|Optional|Or|OrElse|Overloads|Overridable|Overrides|ParamArray|Preserve|Private|Property|Protected|Public|RaiseEvent|ReadOnly|ReDim|RemoveHandler|Resume|Return|Select|Set|Shadows|Shared|Short|Single|Static|Step|Stop|String|Structure|Sub|SyncLock|Then|Throw|To|Try|TypeOf|Unicode|Until|Variant|Wend|When|While|With|WithEvents|WriteOnly|Xor|EndIf|GoSub|Let|Variant|Wend)\b/i, null], // A second comment form [PR.PR_COMMENT, /^REM[^\r\n\u2028\u2029]*/i], // A boolean, numeric, or date literal. [PR.PR_LITERAL, /^(?:True\b|False\b|Nothing\b|\d+(?:E[+\-]?\d+[FRD]?|[FRDSIL])?|(?:&H[0-9A-F]+|&O[0-7]+)[SIL]?|\d*\.\d+(?:E[+\-]?\d+)?[FRD]?|#\s+(?:\d+[\-\/]\d+[\-\/]\d+(?:\s+\d+:\d+(?::\d+)?(\s*(?:AM|PM))?)?|\d+:\d+(?::\d+)?(\s*(?:AM|PM))?)\s+#)/i], // An identifier? [PR.PR_PLAIN, /^(?:(?:[a-z]|_\w)\w*|\[(?:[a-z]|_\w)\w*\])/i], // A run of punctuation [PR.PR_PUNCTUATION, /^[^\w\t\n\r \"\'\[\]\xA0\u2018\u2019\u201C\u201D\u2028\u2029]+/], // Square brackets [PR.PR_PUNCTUATION, /^(?:\[|\])/] ]), ['vb', 'vbs']);
zzcode
trunk/google-code-prettify/lang-vb.js
JavaScript
bsd
3,481
/* Pretty printing styles. Used with prettify.js. */ .str { color: #080; } .kwd { color: #008; } .com { color: #800; } .typ { color: #606; } .lit { color: #066; } .pun { color: #660; } .pln { color: #000; } .tag { color: #008; } .atn { color: #606; } .atv { color: #080; } .dec { color: #606; } pre.prettyprint { padding: 2px; border: 1px solid #888; /* 可以改成用js在页面加载完成后动态调整 */ width: 574px; overflow-y:hidden; background: #FFFFFF url(code-bg.gif) repeat scroll 0 0;} @media print { .str { color: #060; } .kwd { color: #006; font-weight: bold; } .com { color: #600; font-style: italic; } .typ { color: #404; font-weight: bold; } .lit { color: #044; } .pun { color: #440; } .pln { color: #000; } .tag { color: #006; font-weight: bold; } .atn { color: #404; } .atv { color: #060; } }
zzcode
trunk/google-code-prettify/prettify.css
CSS
bsd
849
// Copyright (C) 2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview * Registers a language handler for Wiki pages. * * Based on WikiSyntax at http://code.google.com/p/support/wiki/WikiSyntax * * @author mikesamuel@gmail.com */ PR.registerLangHandler( PR.createSimpleLexer( [ // Whitespace [PR.PR_PLAIN, /^[\t \xA0a-gi-z0-9]+/, null, '\t \xA0abcdefgijklmnopqrstuvwxyz0123456789'], // Wiki formatting [PR.PR_PUNCTUATION, /^[=*~\^\[\]]+/, null, '=*~^[]'] ], [ // Meta-info like #summary, #labels, etc. ['lang-wiki.meta', /(?:^^|\r\n?|\n)(#[a-z]+)\b/], // A WikiWord [PR.PR_LITERAL, /^(?:[A-Z][a-z][a-z0-9]+[A-Z][a-z][a-zA-Z0-9]+)\b/ ], // A preformatted block in an unknown language ['lang-', /^\{\{\{([\s\S]+?)\}\}\}/], // A block of source code in an unknown language ['lang-', /^`([^\r\n`]+)`/], // An inline URL. [PR.PR_STRING, /^https?:\/\/[^\/?#\s]*(?:\/[^?#\s]*)?(?:\?[^#\s]*)?(?:#\S*)?/i], [PR.PR_PLAIN, /^(?:\r\n|[\s\S])[^#=*~^A-Zh\{`\[\r\n]*/] ]), ['wiki']); PR.registerLangHandler( PR.createSimpleLexer([[PR.PR_KEYWORD, /^#[a-z]+/i, null, '#']], []), ['wiki.meta']);
zzcode
trunk/google-code-prettify/lang-wiki.js
JavaScript
bsd
1,881
// Copyright (C) 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview * Registers a language handler for SQL. * * * To use, include prettify.js and this file in your HTML page. * Then put your code in an HTML tag like * <pre class="prettyprint lang-sql">(my SQL code)</pre> * * * http://savage.net.au/SQL/sql-99.bnf.html is the basis for the grammar, and * http://msdn.microsoft.com/en-us/library/aa238507(SQL.80).aspx as the basis * for the keyword list. * * @author mikesamuel@gmail.com */ PR.registerLangHandler( PR.createSimpleLexer( [ // Whitespace [PR.PR_PLAIN, /^[\t\n\r \xA0]+/, null, '\t\n\r \xA0'], // A double or single quoted, possibly multi-line, string. [PR.PR_STRING, /^(?:"(?:[^\"\\]|\\.)*"|'(?:[^\'\\]|\\.)*')/, null, '"\''] ], [ // A comment is either a line comment that starts with two dashes, or // two dashes preceding a long bracketed block. [PR.PR_COMMENT, /^(?:--[^\r\n]*|\/\*[\s\S]*?(?:\*\/|$))/], [PR.PR_KEYWORD, /^(?:ADD|ALL|ALTER|AND|ANY|AS|ASC|AUTHORIZATION|BACKUP|BEGIN|BETWEEN|BREAK|BROWSE|BULK|BY|CASCADE|CASE|CHECK|CHECKPOINT|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMN|COMMIT|COMPUTE|CONSTRAINT|CONTAINS|CONTAINSTABLE|CONTINUE|CONVERT|CREATE|CROSS|CURRENT|CURRENT_DATE|CURRENT_TIME|CURRENT_TIMESTAMP|CURRENT_USER|CURSOR|DATABASE|DBCC|DEALLOCATE|DECLARE|DEFAULT|DELETE|DENY|DESC|DISK|DISTINCT|DISTRIBUTED|DOUBLE|DROP|DUMMY|DUMP|ELSE|END|ERRLVL|ESCAPE|EXCEPT|EXEC|EXECUTE|EXISTS|EXIT|FETCH|FILE|FILLFACTOR|FOR|FOREIGN|FREETEXT|FREETEXTTABLE|FROM|FULL|FUNCTION|GOTO|GRANT|GROUP|HAVING|HOLDLOCK|IDENTITY|IDENTITYCOL|IDENTITY_INSERT|IF|IN|INDEX|INNER|INSERT|INTERSECT|INTO|IS|JOIN|KEY|KILL|LEFT|LIKE|LINENO|LOAD|NATIONAL|NOCHECK|NONCLUSTERED|NOT|NULL|NULLIF|OF|OFF|OFFSETS|ON|OPEN|OPENDATASOURCE|OPENQUERY|OPENROWSET|OPENXML|OPTION|OR|ORDER|OUTER|OVER|PERCENT|PLAN|PRECISION|PRIMARY|PRINT|PROC|PROCEDURE|PUBLIC|RAISERROR|READ|READTEXT|RECONFIGURE|REFERENCES|REPLICATION|RESTORE|RESTRICT|RETURN|REVOKE|RIGHT|ROLLBACK|ROWCOUNT|ROWGUIDCOL|RULE|SAVE|SCHEMA|SELECT|SESSION_USER|SET|SETUSER|SHUTDOWN|SOME|STATISTICS|SYSTEM_USER|TABLE|TEXTSIZE|THEN|TO|TOP|TRAN|TRANSACTION|TRIGGER|TRUNCATE|TSEQUAL|UNION|UNIQUE|UPDATE|UPDATETEXT|USE|USER|VALUES|VARYING|VIEW|WAITFOR|WHEN|WHERE|WHILE|WITH|WRITETEXT)(?=[^\w-]|$)/i, null], // A number is a hex integer literal, a decimal real literal, or in // scientific notation. [PR.PR_LITERAL, /^[+-]?(?:0x[\da-f]+|(?:(?:\.\d+|\d+(?:\.\d*)?)(?:e[+\-]?\d+)?))/i], // An identifier [PR.PR_PLAIN, /^[a-z_][\w-]*/i], // A run of punctuation [PR.PR_PUNCTUATION, /^[^\w\t\n\r \xA0]+/] ]), ['sql']);
zzcode
trunk/google-code-prettify/lang-sql.js
JavaScript
bsd
3,320
// Copyright (C) 2006 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview * Registers a language handler for Protocol Buffers as described at * http://code.google.com/p/protobuf/. * * Based on the lexical grammar at * http://research.microsoft.com/fsharp/manual/spec2.aspx#_Toc202383715 * * @author mikesamuel@gmail.com */ PR.registerLangHandler(PR.sourceDecorator({ keywords: ( 'bool bytes default double enum extend extensions false fixed32 ' + 'fixed64 float group import int32 int64 max message option ' + 'optional package repeated required returns rpc service ' + 'sfixed32 sfixed64 sint32 sint64 string syntax to true uint32 ' + 'uint64'), cStyleComments: true }), ['proto']);
zzcode
trunk/google-code-prettify/lang-proto.js
JavaScript
bsd
1,317
// Copyright (C) 2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview * Registers a language handler for CSS. * * * To use, include prettify.js and this file in your HTML page. * Then put your code in an HTML tag like * <pre class="prettyprint lang-css"></pre> * * * http://www.w3.org/TR/CSS21/grammar.html Section G2 defines the lexical * grammar. This scheme does not recognize keywords containing escapes. * * @author mikesamuel@gmail.com */ PR.registerLangHandler( PR.createSimpleLexer( [ // The space production <s> [PR.PR_PLAIN, /^[ \t\r\n\f]+/, null, ' \t\r\n\f'] ], [ // Quoted strings. <string1> and <string2> [PR.PR_STRING, /^\"(?:[^\n\r\f\\\"]|\\(?:\r\n?|\n|\f)|\\[\s\S])*\"/, null], [PR.PR_STRING, /^\'(?:[^\n\r\f\\\']|\\(?:\r\n?|\n|\f)|\\[\s\S])*\'/, null], ['lang-css-str', /^url\(([^\)\"\']*)\)/i], [PR.PR_KEYWORD, /^(?:url|rgb|\!important|@import|@page|@media|@charset|inherit)(?=[^\-\w]|$)/i, null], // A property name -- an identifier followed by a colon. ['lang-css-kw', /^(-?(?:[_a-z]|(?:\\[0-9a-f]+ ?))(?:[_a-z0-9\-]|\\(?:\\[0-9a-f]+ ?))*)\s*:/i], // A C style block comment. The <comment> production. [PR.PR_COMMENT, /^\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\//], // Escaping text spans [PR.PR_COMMENT, /^(?:<!--|-->)/], // A number possibly containing a suffix. [PR.PR_LITERAL, /^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i], // A hex color [PR.PR_LITERAL, /^#(?:[0-9a-f]{3}){1,2}/i], // An identifier [PR.PR_PLAIN, /^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i], // A run of punctuation [PR.PR_PUNCTUATION, /^[^\s\w\'\"]+/] ]), ['css']); PR.registerLangHandler( PR.createSimpleLexer([], [ [PR.PR_KEYWORD, /^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i] ]), ['css-kw']); PR.registerLangHandler( PR.createSimpleLexer([], [ [PR.PR_STRING, /^[^\)\"\']+/] ]), ['css-str']);
zzcode
trunk/google-code-prettify/lang-css.js
JavaScript
bsd
2,746
// Copyright (C) 2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview * Registers a language handler for Haskell. * * * To use, include prettify.js and this file in your HTML page. * Then put your code in an HTML tag like * <pre class="prettyprint lang-hs">(my lisp code)</pre> * The lang-cl class identifies the language as common lisp. * This file supports the following language extensions: * lang-cl - Common Lisp * lang-el - Emacs Lisp * lang-lisp - Lisp * lang-scm - Scheme * * * I used http://www.informatik.uni-freiburg.de/~thiemann/haskell/haskell98-report-html/syntax-iso.html * as the basis, but ignore the way the ncomment production nests since this * makes the lexical grammar irregular. It might be possible to support * ncomments using the lookbehind filter. * * * @author mikesamuel@gmail.com */ PR.registerLangHandler( PR.createSimpleLexer( [ // Whitespace // whitechar -> newline | vertab | space | tab | uniWhite // newline -> return linefeed | return | linefeed | formfeed [PR.PR_PLAIN, /^[\t\n\x0B\x0C\r ]+/, null, '\t\n\x0B\x0C\r '], // Single line double and single-quoted strings. // char -> ' (graphic<' | \> | space | escape<\&>) ' // string -> " {graphic<" | \> | space | escape | gap}" // escape -> \ ( charesc | ascii | decimal | o octal // | x hexadecimal ) // charesc -> a | b | f | n | r | t | v | \ | " | ' | & [PR.PR_STRING, /^\"(?:[^\"\\\n\x0C\r]|\\[\s\S])*(?:\"|$)/, null, '"'], [PR.PR_STRING, /^\'(?:[^\'\\\n\x0C\r]|\\[^&])\'?/, null, "'"], // decimal -> digit{digit} // octal -> octit{octit} // hexadecimal -> hexit{hexit} // integer -> decimal // | 0o octal | 0O octal // | 0x hexadecimal | 0X hexadecimal // float -> decimal . decimal [exponent] // | decimal exponent // exponent -> (e | E) [+ | -] decimal [PR.PR_LITERAL, /^(?:0o[0-7]+|0x[\da-f]+|\d+(?:\.\d+)?(?:e[+\-]?\d+)?)/i, null, '0123456789'] ], [ // Haskell does not have a regular lexical grammar due to the nested // ncomment. // comment -> dashes [ any<symbol> {any}] newline // ncomment -> opencom ANYseq {ncomment ANYseq}closecom // dashes -> '--' {'-'} // opencom -> '{-' // closecom -> '-}' [PR.PR_COMMENT, /^(?:(?:--+(?:[^\r\n\x0C]*)?)|(?:\{-(?:[^-]|-+[^-\}])*-\}))/], // reservedid -> case | class | data | default | deriving | do // | else | if | import | in | infix | infixl | infixr // | instance | let | module | newtype | of | then // | type | where | _ [PR.PR_KEYWORD, /^(?:case|class|data|default|deriving|do|else|if|import|in|infix|infixl|infixr|instance|let|module|newtype|of|then|type|where|_)(?=[^a-zA-Z0-9\']|$)/, null], // qvarid -> [ modid . ] varid // qconid -> [ modid . ] conid // varid -> (small {small | large | digit | ' })<reservedid> // conid -> large {small | large | digit | ' } // modid -> conid // small -> ascSmall | uniSmall | _ // ascSmall -> a | b | ... | z // uniSmall -> any Unicode lowercase letter // large -> ascLarge | uniLarge // ascLarge -> A | B | ... | Z // uniLarge -> any uppercase or titlecase Unicode letter [PR.PR_PLAIN, /^(?:[A-Z][\w\']*\.)*[a-zA-Z][\w\']*/], // matches the symbol production [PR.PR_PUNCTUATION, /^[^\t\n\x0B\x0C\r a-zA-Z0-9\'\"]+/] ]), ['hs']);
zzcode
trunk/google-code-prettify/lang-hs.js
JavaScript
bsd
4,619
// Copyright (C) 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview * Registers a language handler for Common Lisp and related languages. * * * To use, include prettify.js and this file in your HTML page. * Then put your code in an HTML tag like * <pre class="prettyprint lang-lisp">(my lisp code)</pre> * The lang-cl class identifies the language as common lisp. * This file supports the following language extensions: * lang-cl - Common Lisp * lang-el - Emacs Lisp * lang-lisp - Lisp * lang-scm - Scheme * * * I used http://www.devincook.com/goldparser/doc/meta-language/grammar-LISP.htm * as the basis, but added line comments that start with ; and changed the atom * production to disallow unquoted semicolons. * * "Name" = 'LISP' * "Author" = 'John McCarthy' * "Version" = 'Minimal' * "About" = 'LISP is an abstract language that organizes ALL' * | 'data around "lists".' * * "Start Symbol" = [s-Expression] * * {Atom Char} = {Printable} - {Whitespace} - [()"\''] * * Atom = ( {Atom Char} | '\'{Printable} )+ * * [s-Expression] ::= [Quote] Atom * | [Quote] '(' [Series] ')' * | [Quote] '(' [s-Expression] '.' [s-Expression] ')' * * [Series] ::= [s-Expression] [Series] * | * * [Quote] ::= '' !Quote = do not evaluate * | * * * I used <a href="http://gigamonkeys.com/book/">Practical Common Lisp</a> as * the basis for the reserved word list. * * * @author mikesamuel@gmail.com */ PR.registerLangHandler( PR.createSimpleLexer( [ ['opn', /^\(/, null, '('], ['clo', /^\)/, null, ')'], // A line comment that starts with ; [PR.PR_COMMENT, /^;[^\r\n]*/, null, ';'], // Whitespace [PR.PR_PLAIN, /^[\t\n\r \xA0]+/, null, '\t\n\r \xA0'], // A double quoted, possibly multi-line, string. [PR.PR_STRING, /^\"(?:[^\"\\]|\\[\s\S])*(?:\"|$)/, null, '"'] ], [ [PR.PR_KEYWORD, /^(?:block|c[ad]+r|catch|cons|defun|do|eq|eql|equal|equalp|eval-when|flet|format|go|if|labels|lambda|let|load-time-value|locally|macrolet|multiple-value-call|nil|progn|progv|quote|require|return-from|setq|symbol-macrolet|t|tagbody|the|throw|unwind)\b/, null], [PR.PR_LITERAL, /^[+\-]?(?:0x[0-9a-f]+|\d+\/\d+|(?:\.\d+|\d+(?:\.\d*)?)(?:[ed][+\-]?\d+)?)/i], // A single quote possibly followed by a word that optionally ends with // = ! or ?. [PR.PR_LITERAL, /^\'(?:-*(?:\w|\\[\x21-\x7e])(?:[\w-]*|\\[\x21-\x7e])[=!?]?)?/], // A word that optionally ends with = ! or ?. [PR.PR_PLAIN, /^-*(?:[a-z_]|\\[\x21-\x7e])(?:[\w-]*|\\[\x21-\x7e])[=!?]?/i], // A printable non-space non-special character [PR.PR_PUNCTUATION, /^[^\w\t\n\r \xA0()\"\\\';]+/] ]), ['cl', 'el', 'lisp', 'scm']);
zzcode
trunk/google-code-prettify/lang-lisp.js
JavaScript
bsd
3,507
// Copyright (C) 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview * Registers a language handler for OCaml, SML, F# and similar languages. * * Based on the lexical grammar at * http://research.microsoft.com/fsharp/manual/spec2.aspx#_Toc202383715 * * @author mikesamuel@gmail.com */ PR.registerLangHandler( PR.createSimpleLexer( [ // Whitespace is made up of spaces, tabs and newline characters. [PR.PR_PLAIN, /^[\t\n\r \xA0]+/, null, '\t\n\r \xA0'], // #if ident/#else/#endif directives delimit conditional compilation // sections [PR.PR_COMMENT, /^#(?:if[\t\n\r \xA0]+(?:[a-z_$][\w\']*|``[^\r\n\t`]*(?:``|$))|else|endif|light)/i, null, '#'], // A double or single quoted, possibly multi-line, string. // F# allows escaped newlines in strings. [PR.PR_STRING, /^(?:\"(?:[^\"\\]|\\[\s\S])*(?:\"|$)|\'(?:[^\'\\]|\\[\s\S])*(?:\'|$))/, null, '"\''] ], [ // Block comments are delimited by (* and *) and may be // nested. Single-line comments begin with // and extend to // the end of a line. // TODO: (*...*) comments can be nested. This does not handle that. [PR.PR_COMMENT, /^(?:\/\/[^\r\n]*|\(\*[\s\S]*?\*\))/], [PR.PR_KEYWORD, /^(?:abstract|and|as|assert|begin|class|default|delegate|do|done|downcast|downto|elif|else|end|exception|extern|false|finally|for|fun|function|if|in|inherit|inline|interface|internal|lazy|let|match|member|module|mutable|namespace|new|null|of|open|or|override|private|public|rec|return|static|struct|then|to|true|try|type|upcast|use|val|void|when|while|with|yield|asr|land|lor|lsl|lsr|lxor|mod|sig|atomic|break|checked|component|const|constraint|constructor|continue|eager|event|external|fixed|functor|global|include|method|mixin|object|parallel|process|protected|pure|sealed|trait|virtual|volatile)\b/], // A number is a hex integer literal, a decimal real literal, or in // scientific notation. [PR.PR_LITERAL, /^[+\-]?(?:0x[\da-f]+|(?:(?:\.\d+|\d+(?:\.\d*)?)(?:e[+\-]?\d+)?))/i], [PR.PR_PLAIN, /^(?:[a-z_]\w*[!?#]?|``[^\r\n\t`]*(?:``|$))/i], // A printable non-space non-special character [PR.PR_PUNCTUATION, /^[^\t\n\r \xA0\"\'\w]+/] ]), ['fs', 'ml']);
zzcode
trunk/google-code-prettify/lang-ml.js
JavaScript
bsd
2,917
// Copyright (C) 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview * Registers a language handler for LUA. * * * To use, include prettify.js and this file in your HTML page. * Then put your code in an HTML tag like * <pre class="prettyprint lang-lua">(my LUA code)</pre> * * * I used http://www.lua.org/manual/5.1/manual.html#2.1 * Because of the long-bracket concept used in strings and comments, LUA does * not have a regular lexical grammar, but luckily it fits within the space * of irregular grammars supported by javascript regular expressions. * * @author mikesamuel@gmail.com */ PR.registerLangHandler( PR.createSimpleLexer( [ // Whitespace [PR.PR_PLAIN, /^[\t\n\r \xA0]+/, null, '\t\n\r \xA0'], // A double or single quoted, possibly multi-line, string. [PR.PR_STRING, /^(?:\"(?:[^\"\\]|\\[\s\S])*(?:\"|$)|\'(?:[^\'\\]|\\[\s\S])*(?:\'|$))/, null, '"\''] ], [ // A comment is either a line comment that starts with two dashes, or // two dashes preceding a long bracketed block. [PR.PR_COMMENT, /^--(?:\[(=*)\[[\s\S]*?(?:\]\1\]|$)|[^\r\n]*)/], // A long bracketed block not preceded by -- is a string. [PR.PR_STRING, /^\[(=*)\[[\s\S]*?(?:\]\1\]|$)/], [PR.PR_KEYWORD, /^(?:and|break|do|else|elseif|end|false|for|function|if|in|local|nil|not|or|repeat|return|then|true|until|while)\b/, null], // A number is a hex integer literal, a decimal real literal, or in // scientific notation. [PR.PR_LITERAL, /^[+-]?(?:0x[\da-f]+|(?:(?:\.\d+|\d+(?:\.\d*)?)(?:e[+\-]?\d+)?))/i], // An identifier [PR.PR_PLAIN, /^[a-z_]\w*/i], // A run of punctuation [PR.PR_PUNCTUATION, /^[^\w\t\n\r \xA0][^\w\t\n\r \xA0\"\-\+=]*/] ]), ['lua']);
zzcode
trunk/google-code-prettify/lang-lua.js
JavaScript
bsd
2,411
///////////////////////////////////////////////////////////////////////// // // CSizingControlBarCF Version 2.44 // // Created: Dec 21, 1998 Last Modified: March 31, 2002 // // See the official site at www.datamekanix.com for documentation and // the latest news. // ///////////////////////////////////////////////////////////////////////// // Copyright (C) 1998-2002 by Cristi Posea. All rights reserved. // // This code is free for personal and commercial use, providing this // notice remains intact in the source files and all eventual changes are // clearly marked with comments. // // You must obtain the author's consent before you can include this code // in a software library. // // No warrantee of any kind, express or implied, is included with this // software; use at your own risk, responsibility for damages (if any) to // anyone resulting from the use of this software rests entirely with the // user. // // Send bug reports, bug fixes, enhancements, requests, flames, etc. to // cristi@datamekanix.com or post them at the message board at the site. ///////////////////////////////////////////////////////////////////////// #if !defined(__SCBARCF_H__) #define __SCBARCF_H__ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 // scbarcf.h : header file // ///////////////////////////////////////////////////////////////////////// // CSizingControlBarCF #ifndef baseCSizingControlBarCF #define baseCSizingControlBarCF CSizingControlBarG #endif class CSizingControlBarCF : public baseCSizingControlBarCF { DECLARE_DYNAMIC(CSizingControlBarCF) // Construction public: CSizingControlBarCF(); // Overridables virtual void OnUpdateCmdUI(CFrameWnd* pTarget, BOOL bDisableIfNoHndler); // Implementation protected: // implementation helpers virtual void NcPaintGripper(CDC* pDC, CRect rcClient); protected: BOOL m_bActive; // a child has focus CString m_sFontFace; // Generated message map functions protected: //{{AFX_MSG(CSizingControlBarCF) //}}AFX_MSG afx_msg LRESULT OnSetText(WPARAM wParam, LPARAM lParam); DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////// #endif // !defined(__SCBARCF_H__)
zzh-project-test
branches/ThumbViewer/src/control_bar/scbarcf.h
C++
asf20
2,316
///////////////////////////////////////////////////////////////////////// // // CSizingControlBar Version 2.44 // // Created: Jan 24, 1998 Last Modified: March 31, 2002 // // See the official site at www.datamekanix.com for documentation and // the latest news. // ///////////////////////////////////////////////////////////////////////// // Copyright (C) 1998-2002 by Cristi Posea. All rights reserved. // // This code is free for personal and commercial use, providing this // notice remains intact in the source files and all eventual changes are // clearly marked with comments. // // You must obtain the author's consent before you can include this code // in a software library. // // No warrantee of any kind, express or implied, is included with this // software; use at your own risk, responsibility for damages (if any) to // anyone resulting from the use of this software rests entirely with the // user. // // Send bug reports, bug fixes, enhancements, requests, flames, etc. to // cristi@datamekanix.com or post them at the message board at the site. // // The sources and a short version of the docs are also available at // www.codeproject.com . Look for a "Docking Windows" section and check // the version to be sure you get the latest one ;) // // Hint: These classes are intended to be used as base classes. Do not // simply add your code to these files - instead create a new class // derived from one of CSizingControlBarXX classes and put there what // you need. See CMyBar classes in the demo projects for examples. // Modify this file only to fix bugs, and don't forget to send me a copy. ///////////////////////////////////////////////////////////////////////// // Acknowledgements: // o Thanks to Harlan R. Seymour for his continuous support during // development of this code. // o Thanks to Dundas Software for the opportunity // to test this code on real-life applications. // o Some ideas for the gripper came from the CToolBarEx flat toolbar // by Joerg Koenig. Thanks, Joerg! // o Thanks to Robert Wolpow for the code on which CDockContext based // dialgonal resizing is based. // o Thanks to the following people for various bug fixes and/or // enhancements: Chris Maunder, Jakawan Ratiwanich, Udo Schaefer, // Anatoly Ivasyuk, Peter Hauptmann, DJ(?), Pat Kusbel, Aleksey // Malyshev. // o And, of course, many thanks to all of you who used this code, // for the invaluable feedback I received. ///////////////////////////////////////////////////////////////////////// // sizecbar.cpp : implementation file // #include "stdafx.h" //#include "..\StdAfx.h" #include "sizecbar.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////// // CSizingControlBar IMPLEMENT_DYNAMIC(CSizingControlBar, baseCSizingControlBar); CSizingControlBar::CSizingControlBar() { m_szMinHorz = CSize(33, 32); m_szMinVert = CSize(33, 32); m_szMinFloat = CSize(37, 32); m_szHorz = CSize(200, 200); m_szVert = CSize(200, 200); m_szFloat = CSize(200, 200); m_bTracking = FALSE; m_bKeepSize = FALSE; m_bParentSizing = FALSE; m_cxEdge = 5; m_bDragShowContent = FALSE; m_nDockBarID = 0; m_dwSCBStyle = 0; } CSizingControlBar::~CSizingControlBar() { } BEGIN_MESSAGE_MAP(CSizingControlBar, baseCSizingControlBar) //{{AFX_MSG_MAP(CSizingControlBar) ON_WM_CREATE() ON_WM_PAINT() ON_WM_NCPAINT() ON_WM_NCCALCSIZE() ON_WM_WINDOWPOSCHANGING() ON_WM_CAPTURECHANGED() ON_WM_SETTINGCHANGE() ON_WM_LBUTTONUP() ON_WM_MOUSEMOVE() ON_WM_NCLBUTTONDOWN() ON_WM_LBUTTONDOWN() ON_WM_LBUTTONDBLCLK() ON_WM_RBUTTONDOWN() ON_WM_NCMOUSEMOVE() ON_WM_NCHITTEST() ON_WM_CLOSE() ON_WM_SIZE() //}}AFX_MSG_MAP ON_MESSAGE(WM_SETTEXT, OnSetText) END_MESSAGE_MAP() // old creation method, still here for compatibility reasons BOOL CSizingControlBar::Create(LPCTSTR lpszWindowName, CWnd* pParentWnd, CSize sizeDefault, BOOL bHasGripper, UINT nID, DWORD dwStyle) { UNUSED_ALWAYS(bHasGripper); m_szHorz = m_szVert = m_szFloat = sizeDefault; return Create(lpszWindowName, pParentWnd, nID, dwStyle); } // preffered creation method BOOL CSizingControlBar::Create(LPCTSTR lpszWindowName, CWnd* pParentWnd, UINT nID, DWORD dwStyle) { // must have a parent ASSERT_VALID(pParentWnd); // cannot be both fixed and dynamic // (CBRS_SIZE_DYNAMIC is used for resizng when floating) ASSERT (!((dwStyle & CBRS_SIZE_FIXED) && (dwStyle & CBRS_SIZE_DYNAMIC))); m_dwStyle = dwStyle & CBRS_ALL; // save the control bar styles // register and create the window - skip CControlBar::Create() CString wndclass = ::AfxRegisterWndClass(CS_DBLCLKS, ::LoadCursor(NULL, IDC_ARROW), ::GetSysColorBrush(COLOR_BTNFACE), 0); dwStyle &= ~CBRS_ALL; // keep only the generic window styles dwStyle |= WS_CLIPCHILDREN; // prevents flashing if (!CWnd::Create(wndclass, lpszWindowName, dwStyle, CRect(0, 0, 0, 0), pParentWnd, nID)) return FALSE; return TRUE; } ///////////////////////////////////////////////////////////////////////// // CSizingControlBar operations #if defined(_SCB_REPLACE_MINIFRAME) && !defined(_SCB_MINIFRAME_CAPTION) void CSizingControlBar::EnableDocking(DWORD dwDockStyle) { // must be CBRS_ALIGN_XXX or CBRS_FLOAT_MULTI only ASSERT((dwDockStyle & ~(CBRS_ALIGN_ANY|CBRS_FLOAT_MULTI)) == 0); // cannot have the CBRS_FLOAT_MULTI style ASSERT((dwDockStyle & CBRS_FLOAT_MULTI) == 0); // the bar must have CBRS_SIZE_DYNAMIC style ASSERT((m_dwStyle & CBRS_SIZE_DYNAMIC) != 0); m_dwDockStyle = dwDockStyle; if (m_pDockContext == NULL) m_pDockContext = new CSCBDockContext(this); // permanently wire the bar's owner to its current parent if (m_hWndOwner == NULL) m_hWndOwner = ::GetParent(m_hWnd); } #endif ///////////////////////////////////////////////////////////////////////// // CSizingControlBar message handlers int CSizingControlBar::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (baseCSizingControlBar::OnCreate(lpCreateStruct) == -1) return -1; // query SPI_GETDRAGFULLWINDOWS system parameter // OnSettingChange() will update m_bDragShowContent m_bDragShowContent = FALSE; ::SystemParametersInfo(SPI_GETDRAGFULLWINDOWS, 0, &m_bDragShowContent, 0); // uncomment this line if you want raised borders // m_dwSCBStyle |= SCBS_SHOWEDGES; return 0; } LRESULT CSizingControlBar::OnSetText(WPARAM wParam, LPARAM lParam) { UNUSED_ALWAYS(wParam); LRESULT lResult = CWnd::Default(); if (IsFloating() && GetParentFrame()->IsKindOf(RUNTIME_CLASS(CMiniDockFrameWnd))) { m_pDockBar->SetWindowText((LPCTSTR) lParam); // update dockbar GetParentFrame()->DelayRecalcLayout(); // refresh miniframe } return lResult; } const BOOL CSizingControlBar::IsFloating() const { return !IsHorzDocked() && !IsVertDocked(); } const BOOL CSizingControlBar::IsHorzDocked() const { return (m_nDockBarID == AFX_IDW_DOCKBAR_TOP || m_nDockBarID == AFX_IDW_DOCKBAR_BOTTOM); } const BOOL CSizingControlBar::IsVertDocked() const { return (m_nDockBarID == AFX_IDW_DOCKBAR_LEFT || m_nDockBarID == AFX_IDW_DOCKBAR_RIGHT); } const BOOL CSizingControlBar::IsSideTracking() const { // don't call this when not tracking ASSERT(m_bTracking && !IsFloating()); return (m_htEdge == HTLEFT || m_htEdge == HTRIGHT) ? IsHorzDocked() : IsVertDocked(); } CSize CSizingControlBar::CalcFixedLayout(BOOL bStretch, BOOL bHorz) { if (bStretch) // the bar is stretched (is not the child of a dockbar) if (bHorz) return CSize(32767, m_szHorz.cy); else return CSize(m_szVert.cx, 32767); // dirty cast - we need access to protected CDockBar members CSCBDockBar* pDockBar = (CSCBDockBar*) m_pDockBar; // force imediate RecalcDelayShow() for all sizing bars on the row // with delayShow/delayHide flags set to avoid IsVisible() problems CSCBArray arrSCBars; GetRowSizingBars(arrSCBars); AFX_SIZEPARENTPARAMS layout; layout.hDWP = pDockBar->m_bLayoutQuery ? NULL : ::BeginDeferWindowPos(arrSCBars.GetSize()); for (int i = 0; i < arrSCBars.GetSize(); i++) if (arrSCBars[i]->m_nStateFlags & (delayHide|delayShow)) arrSCBars[i]->RecalcDelayShow(&layout); if (layout.hDWP != NULL) ::EndDeferWindowPos(layout.hDWP); // get available length CRect rc = pDockBar->m_rectLayout; if (rc.IsRectEmpty()) m_pDockSite->GetClientRect(&rc); int nLengthTotal = bHorz ? rc.Width() + 2 : rc.Height() - 2; if (IsVisible() && !IsFloating() && m_bParentSizing && arrSCBars[0] == this) if (NegotiateSpace(nLengthTotal, (bHorz != FALSE))) AlignControlBars(); m_bParentSizing = FALSE; if (bHorz) return CSize(max(m_szMinHorz.cx, m_szHorz.cx), max(m_szMinHorz.cy, m_szHorz.cy)); return CSize(max(m_szMinVert.cx, m_szVert.cx), max(m_szMinVert.cy, m_szVert.cy)); } CSize CSizingControlBar::CalcDynamicLayout(int nLength, DWORD dwMode) { if (dwMode & (LM_HORZDOCK | LM_VERTDOCK)) // docked ? { if (nLength == -1) m_bParentSizing = TRUE; return baseCSizingControlBar::CalcDynamicLayout(nLength, dwMode); } if (dwMode & LM_MRUWIDTH) return m_szFloat; if (dwMode & LM_COMMIT) return m_szFloat; // already committed #ifndef _SCB_REPLACE_MINIFRAME // check for dialgonal resizing hit test int nHitTest = m_pDockContext->m_nHitTest; if (IsFloating() && (nHitTest == HTTOPLEFT || nHitTest == HTBOTTOMLEFT || nHitTest == HTTOPRIGHT || nHitTest == HTBOTTOMRIGHT)) { CPoint ptCursor; ::GetCursorPos(&ptCursor); CRect rFrame, rBar; GetParentFrame()->GetWindowRect(&rFrame); GetWindowRect(&rBar); if (nHitTest == HTTOPLEFT || nHitTest == HTBOTTOMLEFT) { m_szFloat.cx = rFrame.left + rBar.Width() - ptCursor.x; m_pDockContext->m_rectFrameDragHorz.left = min(ptCursor.x, rFrame.left + rBar.Width() - m_szMinFloat.cx); } if (nHitTest == HTTOPLEFT || nHitTest == HTTOPRIGHT) { m_szFloat.cy = rFrame.top + rBar.Height() - ptCursor.y; m_pDockContext->m_rectFrameDragHorz.top = min(ptCursor.y, rFrame.top + rBar.Height() - m_szMinFloat.cy); } if (nHitTest == HTTOPRIGHT || nHitTest == HTBOTTOMRIGHT) m_szFloat.cx = rBar.Width() + ptCursor.x - rFrame.right; if (nHitTest == HTBOTTOMLEFT || nHitTest == HTBOTTOMRIGHT) m_szFloat.cy = rBar.Height() + ptCursor.y - rFrame.bottom; } else #endif //_SCB_REPLACE_MINIFRAME ((dwMode & LM_LENGTHY) ? m_szFloat.cy : m_szFloat.cx) = nLength; m_szFloat.cx = max(m_szFloat.cx, m_szMinFloat.cx); m_szFloat.cy = max(m_szFloat.cy, m_szMinFloat.cy); return m_szFloat; } void CSizingControlBar::OnWindowPosChanging(WINDOWPOS FAR* lpwndpos) { // force non-client recalc if moved or resized lpwndpos->flags |= SWP_FRAMECHANGED; baseCSizingControlBar::OnWindowPosChanging(lpwndpos); // find on which side are we docked m_nDockBarID = GetParent()->GetDlgCtrlID(); if (!IsFloating()) if (lpwndpos->flags & SWP_SHOWWINDOW) m_bKeepSize = TRUE; } ///////////////////////////////////////////////////////////////////////// // Mouse Handling // void CSizingControlBar::OnLButtonDown(UINT nFlags, CPoint point) { if (m_pDockBar != NULL) { // start the drag ASSERT(m_pDockContext != NULL); ClientToScreen(&point); m_pDockContext->StartDrag(point); } else CWnd::OnLButtonDown(nFlags, point); } void CSizingControlBar::OnLButtonDblClk(UINT nFlags, CPoint point) { if (m_pDockBar != NULL) { // toggle docking ASSERT(m_pDockContext != NULL); m_pDockContext->ToggleDocking(); } else CWnd::OnLButtonDblClk(nFlags, point); } void CSizingControlBar::OnNcLButtonDown(UINT nHitTest, CPoint point) { UNUSED_ALWAYS(point); if (m_bTracking || IsFloating()) return; if ((nHitTest >= HTSIZEFIRST) && (nHitTest <= HTSIZELAST)) StartTracking(nHitTest, point); // sizing edge hit } void CSizingControlBar::OnLButtonUp(UINT nFlags, CPoint point) { if (m_bTracking) StopTracking(); baseCSizingControlBar::OnLButtonUp(nFlags, point); } void CSizingControlBar::OnRButtonDown(UINT nFlags, CPoint point) { if (m_bTracking) StopTracking(); baseCSizingControlBar::OnRButtonDown(nFlags, point); } void CSizingControlBar::OnMouseMove(UINT nFlags, CPoint point) { if (m_bTracking) { CPoint ptScreen = point; ClientToScreen(&ptScreen); OnTrackUpdateSize(ptScreen); } baseCSizingControlBar::OnMouseMove(nFlags, point); } void CSizingControlBar::OnCaptureChanged(CWnd *pWnd) { if (m_bTracking && (pWnd != this)) StopTracking(); baseCSizingControlBar::OnCaptureChanged(pWnd); } void CSizingControlBar::OnNcCalcSize(BOOL bCalcValidRects, NCCALCSIZE_PARAMS FAR* lpncsp) { UNUSED_ALWAYS(bCalcValidRects); #ifndef _SCB_REPLACE_MINIFRAME // Enable diagonal resizing for floating miniframe if (IsFloating()) { CFrameWnd* pFrame = GetParentFrame(); if (pFrame != NULL && pFrame->IsKindOf(RUNTIME_CLASS(CMiniFrameWnd))) { DWORD dwStyle = ::GetWindowLong(pFrame->m_hWnd, GWL_STYLE); if ((dwStyle & MFS_4THICKFRAME) != 0) { pFrame->ModifyStyle(MFS_4THICKFRAME, 0); // clear GetParent()->ModifyStyle(0, WS_CLIPCHILDREN); } } } #endif _SCB_REPLACE_MINIFRAME // compute the the client area m_dwSCBStyle &= ~SCBS_EDGEALL; // add resizing edges between bars on the same row if (!IsFloating() && m_pDockBar != NULL) { CSCBArray arrSCBars; int nThis; GetRowSizingBars(arrSCBars, nThis); BOOL bHorz = IsHorzDocked(); if (nThis > 0) m_dwSCBStyle |= bHorz ? SCBS_EDGELEFT : SCBS_EDGETOP; if (nThis < arrSCBars.GetUpperBound()) m_dwSCBStyle |= bHorz ? SCBS_EDGERIGHT : SCBS_EDGEBOTTOM; } NcCalcClient(&lpncsp->rgrc[0], m_nDockBarID); } void CSizingControlBar::NcCalcClient(LPRECT pRc, UINT nDockBarID) { CRect rc(pRc); rc.DeflateRect(3, 5, 3, 3); if (nDockBarID != AFX_IDW_DOCKBAR_FLOAT) rc.DeflateRect(2, 0, 2, 2); switch(nDockBarID) { case AFX_IDW_DOCKBAR_TOP: m_dwSCBStyle |= SCBS_EDGEBOTTOM; break; case AFX_IDW_DOCKBAR_BOTTOM: m_dwSCBStyle |= SCBS_EDGETOP; break; case AFX_IDW_DOCKBAR_LEFT: m_dwSCBStyle |= SCBS_EDGERIGHT; break; case AFX_IDW_DOCKBAR_RIGHT: m_dwSCBStyle |= SCBS_EDGELEFT; break; } // make room for edges only if they will be painted if (m_dwSCBStyle & SCBS_SHOWEDGES) rc.DeflateRect( (m_dwSCBStyle & SCBS_EDGELEFT) ? m_cxEdge : 0, (m_dwSCBStyle & SCBS_EDGETOP) ? m_cxEdge : 0, (m_dwSCBStyle & SCBS_EDGERIGHT) ? m_cxEdge : 0, (m_dwSCBStyle & SCBS_EDGEBOTTOM) ? m_cxEdge : 0); *pRc = rc; } void CSizingControlBar::OnNcPaint() { // get window DC that is clipped to the non-client area CWindowDC dc(this); // the HDC will be released by the destructor CRect rcClient, rcBar; GetClientRect(rcClient); ClientToScreen(rcClient); GetWindowRect(rcBar); rcClient.OffsetRect(-rcBar.TopLeft()); rcBar.OffsetRect(-rcBar.TopLeft()); CDC mdc; mdc.CreateCompatibleDC(&dc); CBitmap bm; bm.CreateCompatibleBitmap(&dc, rcBar.Width(), rcBar.Height()); CBitmap* pOldBm = mdc.SelectObject(&bm); // draw borders in non-client area CRect rcDraw = rcBar; DrawBorders(&mdc, rcDraw); // erase the NC background mdc.FillRect(rcDraw, CBrush::FromHandle( (HBRUSH) GetClassLong(m_hWnd, GCL_HBRBACKGROUND))); if (m_dwSCBStyle & SCBS_SHOWEDGES) { CRect rcEdge; // paint the sizing edges for (int i = 0; i < 4; i++) if (GetEdgeRect(rcBar, GetEdgeHTCode(i), rcEdge)) mdc.Draw3dRect(rcEdge, ::GetSysColor(COLOR_BTNHIGHLIGHT), ::GetSysColor(COLOR_BTNSHADOW)); } NcPaintGripper(&mdc, rcClient); // client area is not our bussiness :) dc.IntersectClipRect(rcBar); dc.ExcludeClipRect(rcClient); dc.BitBlt(0, 0, rcBar.Width(), rcBar.Height(), &mdc, 0, 0, SRCCOPY); mdc.SelectObject(pOldBm); bm.DeleteObject(); mdc.DeleteDC(); } void CSizingControlBar::NcPaintGripper(CDC* pDC, CRect rcClient) { UNUSED_ALWAYS(pDC); UNUSED_ALWAYS(rcClient); } void CSizingControlBar::OnPaint() { // overridden to skip border painting based on clientrect CPaintDC dc(this); } UINT CSizingControlBar::OnNcHitTest(CPoint point) //LRESULT CSizingControlBar::OnNcHitTest(CPoint point) { CRect rcBar, rcEdge; GetWindowRect(rcBar); if (!IsFloating()) for (int i = 0; i < 4; i++) if (GetEdgeRect(rcBar, GetEdgeHTCode(i), rcEdge)) if (rcEdge.PtInRect(point)) return GetEdgeHTCode(i); return HTCLIENT; } void CSizingControlBar::OnSettingChange(UINT uFlags, LPCTSTR lpszSection) { baseCSizingControlBar::OnSettingChange(uFlags, lpszSection); m_bDragShowContent = FALSE; ::SystemParametersInfo(SPI_GETDRAGFULLWINDOWS, 0, &m_bDragShowContent, 0); // update } void CSizingControlBar::OnSize(UINT nType, int cx, int cy) { UNUSED_ALWAYS(nType); if ((m_dwSCBStyle & SCBS_SIZECHILD) != 0) { // automatic child resizing - only one child is allowed CWnd* pWnd = GetWindow(GW_CHILD); if (pWnd != NULL) { pWnd->MoveWindow(0, 0, cx, cy); ASSERT(pWnd->GetWindow(GW_HWNDNEXT) == NULL); } } } void CSizingControlBar::OnClose() { // do nothing: protection against accidentally destruction by the // child control (i.e. if user hits Esc in a child editctrl) } ///////////////////////////////////////////////////////////////////////// // CSizingControlBar implementation helpers void CSizingControlBar::StartTracking(UINT nHitTest, CPoint point) { SetCapture(); // make sure no updates are pending if (!m_bDragShowContent) RedrawWindow(NULL, NULL, RDW_ALLCHILDREN | RDW_UPDATENOW); m_htEdge = nHitTest; m_bTracking = TRUE; BOOL bHorz = IsHorzDocked(); BOOL bHorzTracking = m_htEdge == HTLEFT || m_htEdge == HTRIGHT; m_nTrackPosOld = bHorzTracking ? point.x : point.y; CRect rcBar, rcEdge; GetWindowRect(rcBar); GetEdgeRect(rcBar, m_htEdge, rcEdge); m_nTrackEdgeOfs = m_nTrackPosOld - (bHorzTracking ? rcEdge.CenterPoint().x : rcEdge.CenterPoint().y); CSCBArray arrSCBars; int nThis; GetRowSizingBars(arrSCBars, nThis); m_nTrackPosMin = m_nTrackPosMax = m_nTrackPosOld; if (!IsSideTracking()) { // calc minwidth as the max minwidth of the sizing bars on row int nMinWidth = bHorz ? m_szMinHorz.cy : m_szMinVert.cx; for (int i = 0; i < arrSCBars.GetSize(); i++) nMinWidth = max(nMinWidth, bHorz ? arrSCBars[i]->m_szMinHorz.cy : arrSCBars[i]->m_szMinVert.cx); int nExcessWidth = (bHorz ? m_szHorz.cy : m_szVert.cx) - nMinWidth; // the control bar cannot grow with more than the width of // remaining client area of the mainframe CRect rcT; m_pDockSite->RepositionBars(0, 0xFFFF, AFX_IDW_PANE_FIRST, reposQuery, &rcT, NULL, TRUE); int nMaxWidth = bHorz ? rcT.Height() - 2 : rcT.Width() - 2; BOOL bTopOrLeft = m_htEdge == HTTOP || m_htEdge == HTLEFT; m_nTrackPosMin -= bTopOrLeft ? nMaxWidth : nExcessWidth; m_nTrackPosMax += bTopOrLeft ? nExcessWidth : nMaxWidth; } else { // side tracking: // max size is the actual size plus the amount the other // sizing bars can be decreased until they reach their minsize if (m_htEdge == HTBOTTOM || m_htEdge == HTRIGHT) nThis++; for (int i = 0; i < arrSCBars.GetSize(); i++) { CSizingControlBar* pBar = arrSCBars[i]; int nExcessWidth = bHorz ? pBar->m_szHorz.cx - pBar->m_szMinHorz.cx : pBar->m_szVert.cy - pBar->m_szMinVert.cy; if (i < nThis) m_nTrackPosMin -= nExcessWidth; else m_nTrackPosMax += nExcessWidth; } } OnTrackInvertTracker(); // draw tracker } void CSizingControlBar::StopTracking() { OnTrackInvertTracker(); // erase tracker m_bTracking = FALSE; ReleaseCapture(); m_pDockSite->DelayRecalcLayout(); } void CSizingControlBar::OnTrackUpdateSize(CPoint& point) { ASSERT(!IsFloating()); BOOL bHorzTrack = m_htEdge == HTLEFT || m_htEdge == HTRIGHT; int nTrackPos = bHorzTrack ? point.x : point.y; nTrackPos = max(m_nTrackPosMin, min(m_nTrackPosMax, nTrackPos)); int nDelta = nTrackPos - m_nTrackPosOld; if (nDelta == 0) return; // no pos change OnTrackInvertTracker(); // erase tracker m_nTrackPosOld = nTrackPos; BOOL bHorz = IsHorzDocked(); CSize sizeNew = bHorz ? m_szHorz : m_szVert; switch (m_htEdge) { case HTLEFT: sizeNew -= CSize(nDelta, 0); break; case HTTOP: sizeNew -= CSize(0, nDelta); break; case HTRIGHT: sizeNew += CSize(nDelta, 0); break; case HTBOTTOM: sizeNew += CSize(0, nDelta); break; } CSCBArray arrSCBars; int nThis; GetRowSizingBars(arrSCBars, nThis); if (!IsSideTracking()) for (int i = 0; i < arrSCBars.GetSize(); i++) { CSizingControlBar* pBar = arrSCBars[i]; // make same width (or height) (bHorz ? pBar->m_szHorz.cy : pBar->m_szVert.cx) = bHorz ? sizeNew.cy : sizeNew.cx; } else { int nGrowingBar = nThis; BOOL bBefore = m_htEdge == HTTOP || m_htEdge == HTLEFT; if (bBefore && nDelta > 0) nGrowingBar--; if (!bBefore && nDelta < 0) nGrowingBar++; if (nGrowingBar != nThis) bBefore = !bBefore; // nGrowing is growing nDelta = abs(nDelta); CSizingControlBar* pBar = arrSCBars[nGrowingBar]; (bHorz ? pBar->m_szHorz.cx : pBar->m_szVert.cy) += nDelta; // the others are shrinking int nFirst = bBefore ? nGrowingBar - 1 : nGrowingBar + 1; int nLimit = bBefore ? -1 : arrSCBars.GetSize(); for (int i = nFirst; nDelta != 0 && i != nLimit; i += (bBefore ? -1 : 1)) { CSizingControlBar* pBar = arrSCBars[i]; int nDeltaT = min(nDelta, (bHorz ? pBar->m_szHorz.cx : pBar->m_szVert.cy) - (bHorz ? pBar->m_szMinHorz.cx : pBar->m_szMinVert.cy)); (bHorz ? pBar->m_szHorz.cx : pBar->m_szVert.cy) -= nDeltaT; nDelta -= nDeltaT; } } OnTrackInvertTracker(); // redraw tracker at new pos if (m_bDragShowContent) m_pDockSite->DelayRecalcLayout(); } void CSizingControlBar::OnTrackInvertTracker() { ASSERT(m_bTracking); if (m_bDragShowContent) return; // don't show tracker if DragFullWindows is on BOOL bHorz = IsHorzDocked(); CRect rc, rcBar, rcDock, rcFrame; GetWindowRect(rcBar); m_pDockBar->GetWindowRect(rcDock); m_pDockSite->GetWindowRect(rcFrame); VERIFY(GetEdgeRect(rcBar, m_htEdge, rc)); if (!IsSideTracking()) rc = bHorz ? CRect(rcDock.left + 1, rc.top, rcDock.right - 1, rc.bottom) : CRect(rc.left, rcDock.top + 1, rc.right, rcDock.bottom - 1); BOOL bHorzTracking = m_htEdge == HTLEFT || m_htEdge == HTRIGHT; int nOfs = m_nTrackPosOld - m_nTrackEdgeOfs; nOfs -= bHorzTracking ? rc.CenterPoint().x : rc.CenterPoint().y; rc.OffsetRect(bHorzTracking ? nOfs : 0, bHorzTracking ? 0 : nOfs); rc.OffsetRect(-rcFrame.TopLeft()); CDC *pDC = m_pDockSite->GetDCEx(NULL, DCX_WINDOW | DCX_CACHE | DCX_LOCKWINDOWUPDATE); CBrush* pBrush = CDC::GetHalftoneBrush(); CBrush* pBrushOld = pDC->SelectObject(pBrush); pDC->PatBlt(rc.left, rc.top, rc.Width(), rc.Height(), PATINVERT); pDC->SelectObject(pBrushOld); m_pDockSite->ReleaseDC(pDC); } BOOL CSizingControlBar::GetEdgeRect(CRect rcWnd, UINT nHitTest, CRect& rcEdge) { rcEdge = rcWnd; if (m_dwSCBStyle & SCBS_SHOWEDGES) rcEdge.DeflateRect(1, 1); BOOL bHorz = IsHorzDocked(); switch (nHitTest) { case HTLEFT: if (!(m_dwSCBStyle & SCBS_EDGELEFT)) return FALSE; rcEdge.right = rcEdge.left + m_cxEdge; rcEdge.DeflateRect(0, bHorz ? m_cxEdge: 0); break; case HTTOP: if (!(m_dwSCBStyle & SCBS_EDGETOP)) return FALSE; rcEdge.bottom = rcEdge.top + m_cxEdge; rcEdge.DeflateRect(bHorz ? 0 : m_cxEdge, 0); break; case HTRIGHT: if (!(m_dwSCBStyle & SCBS_EDGERIGHT)) return FALSE; rcEdge.left = rcEdge.right - m_cxEdge; rcEdge.DeflateRect(0, bHorz ? m_cxEdge: 0); break; case HTBOTTOM: if (!(m_dwSCBStyle & SCBS_EDGEBOTTOM)) return FALSE; rcEdge.top = rcEdge.bottom - m_cxEdge; rcEdge.DeflateRect(bHorz ? 0 : m_cxEdge, 0); break; default: ASSERT(FALSE); // invalid hit test code } return TRUE; } UINT CSizingControlBar::GetEdgeHTCode(int nEdge) { if (nEdge == 0) return HTLEFT; if (nEdge == 1) return HTTOP; if (nEdge == 2) return HTRIGHT; if (nEdge == 3) return HTBOTTOM; ASSERT(FALSE); // invalid edge code return HTNOWHERE; } void CSizingControlBar::GetRowInfo(int& nFirst, int& nLast, int& nThis) { ASSERT_VALID(m_pDockBar); // verify bounds nThis = m_pDockBar->FindBar(this); ASSERT(nThis != -1); int i, nBars = m_pDockBar->m_arrBars.GetSize(); // find the first and the last bar in row for (nFirst = -1, i = nThis - 1; i >= 0 && nFirst == -1; i--) if (m_pDockBar->m_arrBars[i] == NULL) nFirst = i + 1; for (nLast = -1, i = nThis + 1; i < nBars && nLast == -1; i++) if (m_pDockBar->m_arrBars[i] == NULL) nLast = i - 1; ASSERT((nLast != -1) && (nFirst != -1)); } void CSizingControlBar::GetRowSizingBars(CSCBArray& arrSCBars) { int nThis; // dummy GetRowSizingBars(arrSCBars, nThis); } void CSizingControlBar::GetRowSizingBars(CSCBArray& arrSCBars, int& nThis) { arrSCBars.RemoveAll(); int nFirstT, nLastT, nThisT; GetRowInfo(nFirstT, nLastT, nThisT); nThis = -1; for (int i = nFirstT; i <= nLastT; i++) { CSizingControlBar* pBar = (CSizingControlBar*) m_pDockBar->m_arrBars[i]; if (HIWORD(pBar) == 0) continue; // placeholder if (!pBar->IsVisible()) continue; if (pBar->IsKindOf(RUNTIME_CLASS(CSizingControlBar))) { if (pBar == this) nThis = arrSCBars.GetSize(); arrSCBars.Add(pBar); } } } BOOL CSizingControlBar::NegotiateSpace(int nLengthTotal, BOOL bHorz) { ASSERT(bHorz == IsHorzDocked()); int nFirst, nLast, nThis; GetRowInfo(nFirst, nLast, nThis); int nLengthAvail = nLengthTotal; int nLengthActual = 0; int nLengthMin = 2; int nWidthMax = 0; CSizingControlBar* pBar; int i; for (i = nFirst; i <= nLast; i++) { pBar = (CSizingControlBar*) m_pDockBar->m_arrBars[i]; if (HIWORD(pBar) == 0) continue; // placeholder if (!pBar->IsVisible()) continue; BOOL bIsSizingBar = pBar->IsKindOf(RUNTIME_CLASS(CSizingControlBar)); int nLengthBar; // minimum length of the bar if (bIsSizingBar) nLengthBar = bHorz ? pBar->m_szMinHorz.cx - 2 : pBar->m_szMinVert.cy - 2; else { CRect rcBar; pBar->GetWindowRect(&rcBar); nLengthBar = bHorz ? rcBar.Width() - 2 : rcBar.Height() - 2; } nLengthMin += nLengthBar; if (nLengthMin > nLengthTotal) { // split the row after fixed bar if (i < nThis) { m_pDockBar->m_arrBars.InsertAt(i + 1, (CControlBar*) NULL); return FALSE; } // only this sizebar remains on the row, adjust it to minsize if (i == nThis) { if (bHorz) m_szHorz.cx = m_szMinHorz.cx; else m_szVert.cy = m_szMinVert.cy; return TRUE; // the dockbar will split the row for us } // we have enough bars - go negotiate with them m_pDockBar->m_arrBars.InsertAt(i, (CControlBar*) NULL); nLast = i - 1; break; } if (bIsSizingBar) { nLengthActual += bHorz ? pBar->m_szHorz.cx - 2 : pBar->m_szVert.cy - 2; nWidthMax = max(nWidthMax, bHorz ? pBar->m_szHorz.cy : pBar->m_szVert.cx); } else nLengthAvail -= nLengthBar; } CSCBArray arrSCBars; GetRowSizingBars(arrSCBars); int nNumBars = arrSCBars.GetSize(); int nDelta = nLengthAvail - nLengthActual; // return faster when there is only one sizing bar per row (this one) if (nNumBars == 1) { ASSERT(arrSCBars[0] == this); if (nDelta == 0) return TRUE; m_bKeepSize = FALSE; (bHorz ? m_szHorz.cx : m_szVert.cy) += nDelta; return TRUE; } // make all the bars the same width for (i = 0; i < nNumBars; i++) if (bHorz) arrSCBars[i]->m_szHorz.cy = nWidthMax; else arrSCBars[i]->m_szVert.cx = nWidthMax; // distribute the difference between the bars, // but don't shrink them below their minsizes while (nDelta != 0) { int nDeltaOld = nDelta; for (i = 0; i < nNumBars; i++) { pBar = arrSCBars[i]; int nLMin = bHorz ? pBar->m_szMinHorz.cx : pBar->m_szMinVert.cy; int nL = bHorz ? pBar->m_szHorz.cx : pBar->m_szVert.cy; if ((nL == nLMin) && (nDelta < 0) || // already at min length pBar->m_bKeepSize) // or wants to keep its size continue; // sign of nDelta int nDelta2 = (nDelta == 0) ? 0 : ((nDelta < 0) ? -1 : 1); (bHorz ? pBar->m_szHorz.cx : pBar->m_szVert.cy) += nDelta2; nDelta -= nDelta2; if (nDelta == 0) break; } // clear m_bKeepSize flags if ((nDeltaOld == nDelta) || (nDelta == 0)) for (i = 0; i < nNumBars; i++) arrSCBars[i]->m_bKeepSize = FALSE; } return TRUE; } void CSizingControlBar::AlignControlBars() { int nFirst, nLast, nThis; GetRowInfo(nFirst, nLast, nThis); BOOL bHorz = IsHorzDocked(); BOOL bNeedRecalc = FALSE; int nAlign = bHorz ? -2 : 0; CRect rc, rcDock; m_pDockBar->GetWindowRect(&rcDock); for (int i = nFirst; i <= nLast; i++) { CSizingControlBar* pBar = (CSizingControlBar*) m_pDockBar->m_arrBars[i]; if (HIWORD(pBar) == 0) continue; // placeholder if (!pBar->IsVisible()) continue; pBar->GetWindowRect(&rc); rc.OffsetRect(-rcDock.TopLeft()); if (pBar->IsKindOf(RUNTIME_CLASS(CSizingControlBar))) rc = CRect(rc.TopLeft(), bHorz ? pBar->m_szHorz : pBar->m_szVert); if ((bHorz ? rc.left : rc.top) != nAlign) { if (!bHorz) rc.OffsetRect(0, nAlign - rc.top - 2); else if (m_nDockBarID == AFX_IDW_DOCKBAR_TOP) rc.OffsetRect(nAlign - rc.left, -2); else rc.OffsetRect(nAlign - rc.left, 0); pBar->MoveWindow(rc); bNeedRecalc = TRUE; } nAlign += (bHorz ? rc.Width() : rc.Height()) - 2; } if (bNeedRecalc) m_pDockSite->DelayRecalcLayout(); } void CSizingControlBar::OnUpdateCmdUI(CFrameWnd* pTarget, BOOL bDisableIfNoHndler) { UNUSED_ALWAYS(bDisableIfNoHndler); UNUSED_ALWAYS(pTarget); } void CSizingControlBar::LoadState(LPCTSTR lpszProfileName) { ASSERT_VALID(this); ASSERT(GetSafeHwnd()); // must be called after Create() #if defined(_SCB_REPLACE_MINIFRAME) && !defined(_SCB_MINIFRAME_CAPTION) // compensate the caption miscalculation in CFrameWnd::SetDockState() CDockState state; state.LoadState(lpszProfileName); UINT nID = GetDlgCtrlID(); for (int i = 0; i < state.m_arrBarInfo.GetSize(); i++) { CControlBarInfo* pInfo = (CControlBarInfo*)state.m_arrBarInfo[i]; ASSERT(pInfo != NULL); if (!pInfo->m_bFloating) continue; // this is a floating dockbar - check the ID array for (int j = 0; j < pInfo->m_arrBarID.GetSize(); j++) if ((DWORD) pInfo->m_arrBarID[j] == nID) { // found this bar - offset origin and save settings pInfo->m_pointPos.x++; pInfo->m_pointPos.y += ::GetSystemMetrics(SM_CYSMCAPTION) + 1; pInfo->SaveState(lpszProfileName, i); } } #endif //_SCB_REPLACE_MINIFRAME && !_SCB_MINIFRAME_CAPTION CWinApp* pApp = AfxGetApp(); TCHAR szSection[256]; wsprintf(szSection, _T("%s-SCBar-%d"), lpszProfileName, GetDlgCtrlID()); m_szHorz.cx = max(m_szMinHorz.cx, (int) pApp->GetProfileInt( szSection, _T("sizeHorzCX"), m_szHorz.cx)); m_szHorz.cy = max(m_szMinHorz.cy, (int) pApp->GetProfileInt( szSection, _T("sizeHorzCY"), m_szHorz.cy)); m_szVert.cx = max(m_szMinVert.cx, (int) pApp->GetProfileInt( szSection, _T("sizeVertCX"), m_szVert.cx)); m_szVert.cy = max(m_szMinVert.cy, (int) pApp->GetProfileInt( szSection, _T("sizeVertCY"), m_szVert.cy)); m_szFloat.cx = max(m_szMinFloat.cx, (int) pApp->GetProfileInt( szSection, _T("sizeFloatCX"), m_szFloat.cx)); m_szFloat.cy = max(m_szMinFloat.cy, (int) pApp->GetProfileInt( szSection, _T("sizeFloatCY"), m_szFloat.cy)); } void CSizingControlBar::SaveState(LPCTSTR lpszProfileName) { // place your SaveState or GlobalSaveState call in // CMainFrame's OnClose() or DestroyWindow(), not in OnDestroy() ASSERT_VALID(this); ASSERT(GetSafeHwnd()); CWinApp* pApp = AfxGetApp(); TCHAR szSection[256]; wsprintf(szSection, _T("%s-SCBar-%d"), lpszProfileName, GetDlgCtrlID()); pApp->WriteProfileInt(szSection, _T("sizeHorzCX"), m_szHorz.cx); pApp->WriteProfileInt(szSection, _T("sizeHorzCY"), m_szHorz.cy); pApp->WriteProfileInt(szSection, _T("sizeVertCX"), m_szVert.cx); pApp->WriteProfileInt(szSection, _T("sizeVertCY"), m_szVert.cy); pApp->WriteProfileInt(szSection, _T("sizeFloatCX"), m_szFloat.cx); pApp->WriteProfileInt(szSection, _T("sizeFloatCY"), m_szFloat.cy); } void CSizingControlBar::GlobalLoadState(CFrameWnd* pFrame, LPCTSTR lpszProfileName) { POSITION pos = pFrame->m_listControlBars.GetHeadPosition(); while (pos != NULL) { CSizingControlBar* pBar = (CSizingControlBar*) pFrame->m_listControlBars.GetNext(pos); ASSERT(pBar != NULL); if (pBar->IsKindOf(RUNTIME_CLASS(CSizingControlBar))) pBar->LoadState(lpszProfileName); } } void CSizingControlBar::GlobalSaveState(CFrameWnd* pFrame, LPCTSTR lpszProfileName) { POSITION pos = pFrame->m_listControlBars.GetHeadPosition(); while (pos != NULL) { CSizingControlBar* pBar = (CSizingControlBar*) pFrame->m_listControlBars.GetNext(pos); ASSERT(pBar != NULL); if (pBar->IsKindOf(RUNTIME_CLASS(CSizingControlBar))) pBar->SaveState(lpszProfileName); } } #ifdef _SCB_REPLACE_MINIFRAME #ifndef _SCB_MINIFRAME_CAPTION ///////////////////////////////////////////////////////////////////////////// // CSCBDockContext Drag Operations static void AdjustRectangle(CRect& rect, CPoint pt) { int nXOffset = (pt.x < rect.left) ? (pt.x - rect.left) : (pt.x > rect.right) ? (pt.x - rect.right) : 0; int nYOffset = (pt.y < rect.top) ? (pt.y - rect.top) : (pt.y > rect.bottom) ? (pt.y - rect.bottom) : 0; rect.OffsetRect(nXOffset, nYOffset); } void CSCBDockContext::StartDrag(CPoint pt) { ASSERT_VALID(m_pBar); m_bDragging = TRUE; InitLoop(); ASSERT((m_pBar->m_dwStyle & CBRS_SIZE_DYNAMIC) != 0); // get true bar size (including borders) CRect rect; m_pBar->GetWindowRect(rect); m_ptLast = pt; CSize sizeHorz = m_pBar->CalcDynamicLayout(0, LM_HORZ | LM_HORZDOCK); CSize sizeVert = m_pBar->CalcDynamicLayout(0, LM_VERTDOCK); CSize sizeFloat = m_pBar->CalcDynamicLayout(0, LM_HORZ | LM_MRUWIDTH); m_rectDragHorz = CRect(rect.TopLeft(), sizeHorz); m_rectDragVert = CRect(rect.TopLeft(), sizeVert); // calculate frame dragging rectangle m_rectFrameDragHorz = CRect(rect.TopLeft(), sizeFloat); #ifdef _MAC CMiniFrameWnd::CalcBorders(&m_rectFrameDragHorz, WS_THICKFRAME, WS_EX_FORCESIZEBOX); #else CMiniFrameWnd::CalcBorders(&m_rectFrameDragHorz, WS_THICKFRAME); #endif m_rectFrameDragHorz.DeflateRect(2, 2); m_rectFrameDragVert = m_rectFrameDragHorz; // adjust rectangles so that point is inside AdjustRectangle(m_rectDragHorz, pt); AdjustRectangle(m_rectDragVert, pt); AdjustRectangle(m_rectFrameDragHorz, pt); AdjustRectangle(m_rectFrameDragVert, pt); // initialize tracking state and enter tracking loop m_dwOverDockStyle = CanDock(); Move(pt); // call it here to handle special keys Track(); } #endif //_SCB_MINIFRAME_CAPTION ///////////////////////////////////////////////////////////////////////////// // CSCBMiniDockFrameWnd IMPLEMENT_DYNCREATE(CSCBMiniDockFrameWnd, baseCSCBMiniDockFrameWnd); BEGIN_MESSAGE_MAP(CSCBMiniDockFrameWnd, baseCSCBMiniDockFrameWnd) //{{AFX_MSG_MAP(CSCBMiniDockFrameWnd) ON_WM_NCLBUTTONDOWN() ON_WM_GETMINMAXINFO() ON_WM_WINDOWPOSCHANGING() ON_WM_SIZE() //}}AFX_MSG_MAP END_MESSAGE_MAP() BOOL CSCBMiniDockFrameWnd::Create(CWnd* pParent, DWORD dwBarStyle) { // set m_bInRecalcLayout to avoid flashing during creation // RecalcLayout will be called once something is docked m_bInRecalcLayout = TRUE; DWORD dwStyle = WS_POPUP|WS_CAPTION|WS_SYSMENU|MFS_MOVEFRAME| MFS_4THICKFRAME|MFS_SYNCACTIVE|MFS_BLOCKSYSMENU| FWS_SNAPTOBARS; if (dwBarStyle & CBRS_SIZE_DYNAMIC) dwStyle &= ~MFS_MOVEFRAME; DWORD dwExStyle = 0; #ifdef _MAC if (dwBarStyle & CBRS_SIZE_DYNAMIC) dwExStyle |= WS_EX_FORCESIZEBOX; else dwStyle &= ~(MFS_MOVEFRAME|MFS_4THICKFRAME); #endif if (!CMiniFrameWnd::CreateEx(dwExStyle, NULL, &afxChNil, dwStyle, rectDefault, pParent)) { m_bInRecalcLayout = FALSE; return FALSE; } dwStyle = dwBarStyle & (CBRS_ALIGN_LEFT|CBRS_ALIGN_RIGHT) ? CBRS_ALIGN_LEFT : CBRS_ALIGN_TOP; dwStyle |= dwBarStyle & CBRS_FLOAT_MULTI; CMenu* pSysMenu = GetSystemMenu(FALSE); //pSysMenu->DeleteMenu(SC_SIZE, MF_BYCOMMAND); CString strHide; if (strHide.LoadString(AFX_IDS_HIDE)) { pSysMenu->DeleteMenu(SC_CLOSE, MF_BYCOMMAND); pSysMenu->AppendMenu(MF_STRING|MF_ENABLED, SC_CLOSE, strHide); } // must initially create with parent frame as parent if (!m_wndDockBar.Create(pParent, WS_CHILD | WS_VISIBLE | dwStyle, AFX_IDW_DOCKBAR_FLOAT)) { m_bInRecalcLayout = FALSE; return FALSE; } // set parent to CMiniDockFrameWnd m_wndDockBar.SetParent(this); m_bInRecalcLayout = FALSE; return TRUE; } void CSCBMiniDockFrameWnd::OnNcLButtonDown(UINT nHitTest, CPoint point) { if (nHitTest == HTCAPTION || nHitTest == HTCLOSE) { baseCSCBMiniDockFrameWnd::OnNcLButtonDown(nHitTest, point); return; } if (GetSizingControlBar() != NULL) CMiniFrameWnd::OnNcLButtonDown(nHitTest, point); else baseCSCBMiniDockFrameWnd::OnNcLButtonDown(nHitTest, point); } CSizingControlBar* CSCBMiniDockFrameWnd::GetSizingControlBar() { CWnd* pWnd = GetWindow(GW_CHILD); // get the dockbar if (pWnd == NULL) return NULL; pWnd = pWnd->GetWindow(GW_CHILD); // get the controlbar if (pWnd == NULL) return NULL; if (!pWnd->IsKindOf(RUNTIME_CLASS(CSizingControlBar))) return NULL; return (CSizingControlBar*) pWnd; } void CSCBMiniDockFrameWnd::OnSize(UINT nType, int cx, int cy) { CSizingControlBar* pBar = GetSizingControlBar(); if ((pBar != NULL) && (GetStyle() & MFS_4THICKFRAME) == 0 && pBar->IsVisible() && cx + 4 >= pBar->m_szMinFloat.cx && cy + 4 >= pBar->m_szMinFloat.cy) pBar->m_szFloat = CSize(cx + 4, cy + 4); baseCSCBMiniDockFrameWnd::OnSize(nType, cx, cy); } void CSCBMiniDockFrameWnd::OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI) { baseCSCBMiniDockFrameWnd::OnGetMinMaxInfo(lpMMI); CSizingControlBar* pBar = GetSizingControlBar(); if (pBar != NULL) { CRect r(CPoint(0, 0), pBar->m_szMinFloat - CSize(4, 4)); #ifndef _SCB_MINIFRAME_CAPTION CMiniFrameWnd::CalcBorders(&r, WS_THICKFRAME); #else CMiniFrameWnd::CalcBorders(&r, WS_THICKFRAME|WS_CAPTION); #endif //_SCB_MINIFRAME_CAPTION lpMMI->ptMinTrackSize.x = r.Width(); lpMMI->ptMinTrackSize.y = r.Height(); } } void CSCBMiniDockFrameWnd::OnWindowPosChanging(WINDOWPOS FAR* lpwndpos) { if ((GetStyle() & MFS_4THICKFRAME) != 0) { CSizingControlBar* pBar = GetSizingControlBar(); if (pBar != NULL) { lpwndpos->flags |= SWP_NOSIZE; // don't size this time // prevents flicker pBar->m_pDockBar->ModifyStyle(0, WS_CLIPCHILDREN); // enable diagonal resizing DWORD dwStyleRemove = MFS_4THICKFRAME; #ifndef _SCB_MINIFRAME_CAPTION // remove caption dwStyleRemove |= WS_SYSMENU|WS_CAPTION; #endif ModifyStyle(dwStyleRemove, 0); DelayRecalcLayout(); pBar->PostMessage(WM_NCPAINT); } } CMiniFrameWnd::OnWindowPosChanging(lpwndpos); } #endif //_SCB_REPLACE_MINIFRAME
zzh-project-test
branches/ThumbViewer/src/control_bar/sizecbar.cpp
C++
asf20
44,967
///////////////////////////////////////////////////////////////////////// // // CSizingControlBar Version 2.44 // // Created: Jan 24, 1998 Last Modified: March 31, 2002 // // See the official site at www.datamekanix.com for documentation and // the latest news. // ///////////////////////////////////////////////////////////////////////// // Copyright (C) 1998-2002 by Cristi Posea. All rights reserved. // // This code is free for personal and commercial use, providing this // notice remains intact in the source files and all eventual changes are // clearly marked with comments. // // You must obtain the author's consent before you can include this code // in a software library. // // No warrantee of any kind, express or implied, is included with this // software; use at your own risk, responsibility for damages (if any) to // anyone resulting from the use of this software rests entirely with the // user. // // Send bug reports, bug fixes, enhancements, requests, flames, etc. to // cristi@datamekanix.com or post them at the message board at the site. ///////////////////////////////////////////////////////////////////////// #if !defined(__SIZECBAR_H__) #define __SIZECBAR_H__ #include <afxpriv.h> // for CDockContext #include <afxtempl.h> // for CTypedPtrArray #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #if defined(_SCB_MINIFRAME_CAPTION) && !defined(_SCB_REPLACE_MINIFRAME) #error "_SCB_MINIFRAME_CAPTION requires _SCB_REPLACE_MINIFRAME" #endif ///////////////////////////////////////////////////////////////////////// // CSCBDockBar dummy class for access to protected members class CSCBDockBar : public CDockBar { friend class CSizingControlBar; }; ///////////////////////////////////////////////////////////////////////// // CSizingControlBar control bar styles #define SCBS_EDGELEFT 0x00000001 #define SCBS_EDGERIGHT 0x00000002 #define SCBS_EDGETOP 0x00000004 #define SCBS_EDGEBOTTOM 0x00000008 #define SCBS_EDGEALL 0x0000000F #define SCBS_SHOWEDGES 0x00000010 #define SCBS_SIZECHILD 0x00000020 ///////////////////////////////////////////////////////////////////////// // CSizingControlBar control bar #ifndef baseCSizingControlBar #define baseCSizingControlBar CControlBar #endif class CSizingControlBar; typedef CTypedPtrArray <CPtrArray, CSizingControlBar*> CSCBArray; class CSizingControlBar : public baseCSizingControlBar { DECLARE_DYNAMIC(CSizingControlBar); // Construction public: CSizingControlBar(); virtual BOOL Create(LPCTSTR lpszWindowName, CWnd* pParentWnd, CSize sizeDefault, BOOL bHasGripper, UINT nID, DWORD dwStyle = WS_CHILD | WS_VISIBLE | CBRS_TOP); virtual BOOL Create(LPCTSTR lpszWindowName, CWnd* pParentWnd, UINT nID, DWORD dwStyle = WS_CHILD | WS_VISIBLE | CBRS_TOP); // Attributes public: const BOOL IsFloating() const; const BOOL IsHorzDocked() const; const BOOL IsVertDocked() const; const BOOL IsSideTracking() const; const BOOL GetSCBStyle() const {return m_dwSCBStyle;} // Operations public: #if defined(_SCB_REPLACE_MINIFRAME) && !defined(_SCB_MINIFRAME_CAPTION) void EnableDocking(DWORD dwDockStyle); #endif virtual void LoadState(LPCTSTR lpszProfileName); virtual void SaveState(LPCTSTR lpszProfileName); static void GlobalLoadState(CFrameWnd* pFrame, LPCTSTR lpszProfileName); static void GlobalSaveState(CFrameWnd* pFrame, LPCTSTR lpszProfileName); void SetSCBStyle(DWORD dwSCBStyle) {m_dwSCBStyle = (dwSCBStyle & ~SCBS_EDGEALL);} // Overridables virtual void OnUpdateCmdUI(CFrameWnd* pTarget, BOOL bDisableIfNoHndler); // Overrides public: // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CSizingControlBar) public: virtual CSize CalcFixedLayout(BOOL bStretch, BOOL bHorz); virtual CSize CalcDynamicLayout(int nLength, DWORD dwMode); //}}AFX_VIRTUAL // Implementation public: virtual ~CSizingControlBar(); protected: // implementation helpers UINT GetEdgeHTCode(int nEdge); BOOL GetEdgeRect(CRect rcWnd, UINT nHitTest, CRect& rcEdge); virtual void StartTracking(UINT nHitTest, CPoint point); virtual void StopTracking(); virtual void OnTrackUpdateSize(CPoint& point); virtual void OnTrackInvertTracker(); virtual void NcPaintGripper(CDC* pDC, CRect rcClient); virtual void NcCalcClient(LPRECT pRc, UINT nDockBarID); virtual void AlignControlBars(); void GetRowInfo(int& nFirst, int& nLast, int& nThis); void GetRowSizingBars(CSCBArray& arrSCBars); void GetRowSizingBars(CSCBArray& arrSCBars, int& nThis); BOOL NegotiateSpace(int nLengthTotal, BOOL bHorz); protected: DWORD m_dwSCBStyle; UINT m_htEdge; CSize m_szHorz; CSize m_szVert; CSize m_szFloat; CSize m_szMinHorz; CSize m_szMinVert; CSize m_szMinFloat; int m_nTrackPosMin; int m_nTrackPosMax; int m_nTrackPosOld; int m_nTrackEdgeOfs; BOOL m_bTracking; BOOL m_bKeepSize; BOOL m_bParentSizing; BOOL m_bDragShowContent; UINT m_nDockBarID; int m_cxEdge; // Generated message map functions protected: //{{AFX_MSG(CSizingControlBar) afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnNcPaint(); afx_msg void OnNcCalcSize(BOOL bCalcValidRects, NCCALCSIZE_PARAMS FAR* lpncsp); afx_msg UINT OnNcHitTest(CPoint point); //afx_msg LRESULT OnNcHitTest(CPoint point); afx_msg void OnCaptureChanged(CWnd *pWnd); afx_msg void OnSettingChange(UINT uFlags, LPCTSTR lpszSection); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnNcLButtonDown(UINT nHitTest, CPoint point); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point); afx_msg void OnRButtonDown(UINT nFlags, CPoint point); afx_msg void OnWindowPosChanging(WINDOWPOS FAR* lpwndpos); afx_msg void OnPaint(); afx_msg void OnClose(); afx_msg void OnSize(UINT nType, int cx, int cy); //}}AFX_MSG afx_msg LRESULT OnSetText(WPARAM wParam, LPARAM lParam); DECLARE_MESSAGE_MAP() #ifdef _SCB_REPLACE_MINIFRAME friend class CSCBMiniDockFrameWnd; #endif //_SCB_REPLACE_MINIFRAME }; #ifdef _SCB_REPLACE_MINIFRAME #ifndef _SCB_MINIFRAME_CAPTION ///////////////////////////////////////////////////////////////////////// // CSCBDockContext dockcontext class CSCBDockContext : public CDockContext { public: // Construction CSCBDockContext(CControlBar* pBar) : CDockContext(pBar) {} // Drag Operations virtual void StartDrag(CPoint pt); }; #endif //_SCB_MINIFRAME_CAPTION ///////////////////////////////////////////////////////////////////////// // CSCBMiniDockFrameWnd miniframe #ifndef baseCSCBMiniDockFrameWnd #define baseCSCBMiniDockFrameWnd CMiniDockFrameWnd #endif class CSCBMiniDockFrameWnd : public baseCSCBMiniDockFrameWnd { DECLARE_DYNCREATE(CSCBMiniDockFrameWnd) // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CSCBMiniDockFrameWnd) public: virtual BOOL Create(CWnd* pParent, DWORD dwBarStyle); //}}AFX_VIRTUAL // Implementation public: CSizingControlBar* GetSizingControlBar(); //{{AFX_MSG(CSCBMiniDockFrameWnd) afx_msg void OnNcLButtonDown(UINT nHitTest, CPoint point); afx_msg void OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI); afx_msg void OnWindowPosChanging(WINDOWPOS FAR* lpwndpos); afx_msg void OnSize(UINT nType, int cx, int cy); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #endif //_SCB_REPLACE_MINIFRAME #endif // !defined(__SIZECBAR_H__)
zzh-project-test
branches/ThumbViewer/src/control_bar/sizecbar.h
C++
asf20
8,008
///////////////////////////////////////////////////////////////////////// // // CSizingControlBarG Version 2.44 // // Created: Jan 24, 1998 Last Modified: March 31, 2002 // // See the official site at www.datamekanix.com for documentation and // the latest news. // ///////////////////////////////////////////////////////////////////////// // Copyright (C) 1998-2002 by Cristi Posea. All rights reserved. // // This code is free for personal and commercial use, providing this // notice remains intact in the source files and all eventual changes are // clearly marked with comments. // // You must obtain the author's consent before you can include this code // in a software library. // // No warrantee of any kind, express or implied, is included with this // software; use at your own risk, responsibility for damages (if any) to // anyone resulting from the use of this software rests entirely with the // user. // // Send bug reports, bug fixes, enhancements, requests, flames, etc. to // cristi@datamekanix.com or post them at the message board at the site. ///////////////////////////////////////////////////////////////////////// #if !defined(__SCBARG_H__) #define __SCBARG_H__ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 ///////////////////////////////////////////////////////////////////////// // CSCBButton (button info) helper class class CSCBButton { public: CSCBButton(); void Move(CPoint ptTo) {ptOrg = ptTo; }; CRect GetRect() { return CRect(ptOrg, CSize(11, 11)); }; void Paint(CDC* pDC); BOOL bPushed; BOOL bRaised; protected: CPoint ptOrg; }; ///////////////////////////////////////////////////////////////////////// // CSizingControlBar control bar #ifndef baseCSizingControlBarG #define baseCSizingControlBarG CSizingControlBar #endif class CSizingControlBarG : public baseCSizingControlBarG { DECLARE_DYNAMIC(CSizingControlBarG); // Construction public: CSizingControlBarG(); // Attributes public: virtual BOOL HasGripper() const; // Operations public: // Overridables virtual void OnUpdateCmdUI(CFrameWnd* pTarget, BOOL bDisableIfNoHndler); // Overrides public: // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CSizingControlBarG) //}}AFX_VIRTUAL // Implementation public: virtual ~CSizingControlBarG(); protected: // implementation helpers virtual void NcPaintGripper(CDC* pDC, CRect rcClient); virtual void NcCalcClient(LPRECT pRc, UINT nDockBarID); protected: int m_cyGripper; CSCBButton m_biHide; // Generated message map functions protected: //{{AFX_MSG(CSizingControlBarG) afx_msg UINT OnNcHitTest(CPoint point); //afx_msg LRESULT OnNcHitTest(CPoint point); afx_msg void OnNcLButtonUp(UINT nHitTest, CPoint point); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #endif // !defined(__SCBARG_H__)
zzh-project-test
branches/ThumbViewer/src/control_bar/scbarg.h
C++
asf20
3,020
///////////////////////////////////////////////////////////////////////// // // CSizingControlBarG Version 2.44 // // Created: Jan 24, 1998 Last Modified: March 31, 2002 // // See the official site at www.datamekanix.com for documentation and // the latest news. // ///////////////////////////////////////////////////////////////////////// // Copyright (C) 1998-2002 by Cristi Posea. All rights reserved. // // This code is free for personal and commercial use, providing this // notice remains intact in the source files and all eventual changes are // clearly marked with comments. // // You must obtain the author's consent before you can include this code // in a software library. // // No warrantee of any kind, express or implied, is included with this // software; use at your own risk, responsibility for damages (if any) to // anyone resulting from the use of this software rests entirely with the // user. // // Send bug reports, bug fixes, enhancements, requests, flames, etc. to // cristi@datamekanix.com or post them at the message board at the site. ///////////////////////////////////////////////////////////////////////// // sizecbar.cpp : implementation file // //#include "stdafx.h" #include "..\StdAfx.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////// // CSizingControlBarG IMPLEMENT_DYNAMIC(CSizingControlBarG, baseCSizingControlBarG); CSizingControlBarG::CSizingControlBarG() { m_cyGripper = 12; } CSizingControlBarG::~CSizingControlBarG() { } BEGIN_MESSAGE_MAP(CSizingControlBarG, baseCSizingControlBarG) //{{AFX_MSG_MAP(CSizingControlBarG) ON_WM_NCLBUTTONUP() ON_WM_NCHITTEST() //}}AFX_MSG_MAP ON_MESSAGE(WM_SETTEXT, OnSetText) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////// // CSizingControlBarG message handlers ///////////////////////////////////////////////////////////////////////// // Mouse Handling // void CSizingControlBarG::OnNcLButtonUp(UINT nHitTest, CPoint point) { if (nHitTest == HTCLOSE) m_pDockSite->ShowControlBar(this, FALSE, FALSE); // hide baseCSizingControlBarG::OnNcLButtonUp(nHitTest, point); } void CSizingControlBarG::NcCalcClient(LPRECT pRc, UINT nDockBarID) { CRect rcBar(pRc); // save the bar rect // subtract edges baseCSizingControlBarG::NcCalcClient(pRc, nDockBarID); if (!HasGripper()) return; CRect rc(pRc); // the client rect as calculated by the base class BOOL bHorz = (nDockBarID == AFX_IDW_DOCKBAR_TOP) || (nDockBarID == AFX_IDW_DOCKBAR_BOTTOM); if (bHorz) rc.DeflateRect(m_cyGripper, 0, 0, 0); else rc.DeflateRect(0, m_cyGripper, 0, 0); // set position for the "x" (hide bar) button CPoint ptOrgBtn; if (bHorz) ptOrgBtn = CPoint(rc.left - 13, rc.top); else ptOrgBtn = CPoint(rc.right - 12, rc.top - 13); m_biHide.Move(ptOrgBtn - rcBar.TopLeft()); *pRc = rc; } void CSizingControlBarG::NcPaintGripper(CDC* pDC, CRect rcClient) { if (!HasGripper()) return; // paints a simple "two raised lines" gripper // override this if you want a more sophisticated gripper CRect gripper = rcClient; CRect rcbtn = m_biHide.GetRect(); BOOL bHorz = IsHorzDocked(); gripper.DeflateRect(1, 1); if (bHorz) { // gripper at left gripper.left -= m_cyGripper; gripper.right = gripper.left + 3; gripper.top = rcbtn.bottom + 3; } else { // gripper at top gripper.top -= m_cyGripper; gripper.bottom = gripper.top + 3; gripper.right = rcbtn.left - 3; } pDC->Draw3dRect(gripper, ::GetSysColor(COLOR_BTNHIGHLIGHT), ::GetSysColor(COLOR_BTNSHADOW)); gripper.OffsetRect(bHorz ? 3 : 0, bHorz ? 0 : 3); pDC->Draw3dRect(gripper, ::GetSysColor(COLOR_BTNHIGHLIGHT), ::GetSysColor(COLOR_BTNSHADOW)); m_biHide.Paint(pDC); } UINT CSizingControlBarG::OnNcHitTest(CPoint point) //LRESULT CSizingControlBarG::OnNcHitTest(CPoint point) { CRect rcBar; GetWindowRect(rcBar); UINT nRet = baseCSizingControlBarG::OnNcHitTest(point); if (nRet != HTCLIENT) return nRet; CRect rc = m_biHide.GetRect(); rc.OffsetRect(rcBar.TopLeft()); if (rc.PtInRect(point)) return HTCLOSE; return HTCLIENT; } ///////////////////////////////////////////////////////////////////////// // CSizingControlBarG implementation helpers void CSizingControlBarG::OnUpdateCmdUI(CFrameWnd* pTarget, BOOL bDisableIfNoHndler) { UNUSED_ALWAYS(bDisableIfNoHndler); UNUSED_ALWAYS(pTarget); if (!HasGripper()) return; BOOL bNeedPaint = FALSE; CPoint pt; ::GetCursorPos(&pt); BOOL bHit = (OnNcHitTest(pt) == HTCLOSE); BOOL bLButtonDown = (::GetKeyState(VK_LBUTTON) < 0); BOOL bWasPushed = m_biHide.bPushed; m_biHide.bPushed = bHit && bLButtonDown; BOOL bWasRaised = m_biHide.bRaised; m_biHide.bRaised = bHit && !bLButtonDown; bNeedPaint |= (m_biHide.bPushed ^ bWasPushed) || (m_biHide.bRaised ^ bWasRaised); if (bNeedPaint) SendMessage(WM_NCPAINT); } ///////////////////////////////////////////////////////////////////////// // CSCBButton CSCBButton::CSCBButton() { bRaised = FALSE; bPushed = FALSE; } void CSCBButton::Paint(CDC* pDC) { CRect rc = GetRect(); if (bPushed) pDC->Draw3dRect(rc, ::GetSysColor(COLOR_BTNSHADOW), ::GetSysColor(COLOR_BTNHIGHLIGHT)); else if (bRaised) pDC->Draw3dRect(rc, ::GetSysColor(COLOR_BTNHIGHLIGHT), ::GetSysColor(COLOR_BTNSHADOW)); COLORREF clrOldTextColor = pDC->GetTextColor(); pDC->SetTextColor(::GetSysColor(COLOR_BTNTEXT)); int nPrevBkMode = pDC->SetBkMode(TRANSPARENT); CFont font; int ppi = pDC->GetDeviceCaps(LOGPIXELSX); int pointsize = MulDiv(60, 96, ppi); // 6 points at 96 ppi font.CreatePointFont(pointsize, _T("Marlett")); CFont* oldfont = pDC->SelectObject(&font); pDC->TextOut(ptOrg.x + 2, ptOrg.y + 2, CString(_T("r"))); // x-like pDC->SelectObject(oldfont); pDC->SetBkMode(nPrevBkMode); pDC->SetTextColor(clrOldTextColor); } BOOL CSizingControlBarG::HasGripper() const { #if defined(_SCB_MINIFRAME_CAPTION) || !defined(_SCB_REPLACE_MINIFRAME) // if the miniframe has a caption, don't display the gripper if (IsFloating()) return FALSE; #endif //_SCB_MINIFRAME_CAPTION return TRUE; }
zzh-project-test
branches/ThumbViewer/src/control_bar/scbarg.cpp
C++
asf20
6,904
///////////////////////////////////////////////////////////////////////// // // CSizingControlBarCF Version 2.44 // // Created: Dec 21, 1998 Last Modified: March 31, 2002 // // See the official site at www.datamekanix.com for documentation and // the latest news. // ///////////////////////////////////////////////////////////////////////// // Copyright (C) 1998-2002 by Cristi Posea. All rights reserved. // // This code is free for personal and commercial use, providing this // notice remains intact in the source files and all eventual changes are // clearly marked with comments. // // You must obtain the author's consent before you can include this code // in a software library. // // No warrantee of any kind, express or implied, is included with this // software; use at your own risk, responsibility for damages (if any) to // anyone resulting from the use of this software rests entirely with the // user. // // Send bug reports, bug fixes, enhancements, requests, flames, etc. to // cristi@datamekanix.com or post them at the message board at the site. ///////////////////////////////////////////////////////////////////////// #include <stdafx.h> #include "scbarcf.h" ///////////////////////////////////////////////////////////////////////// // CSizingControlBarCF IMPLEMENT_DYNAMIC(CSizingControlBarCF, baseCSizingControlBarCF); int CALLBACK EnumFontFamProc(ENUMLOGFONT FAR *lpelf, NEWTEXTMETRIC FAR *lpntm, int FontType, LPARAM lParam) { UNUSED_ALWAYS(lpelf); UNUSED_ALWAYS(lpntm); UNUSED_ALWAYS(FontType); UNUSED_ALWAYS(lParam); return 0; } CSizingControlBarCF::CSizingControlBarCF() { m_bActive = FALSE; CDC dc; dc.CreateCompatibleDC(NULL); m_sFontFace = (::EnumFontFamilies(dc.m_hDC, _T("Tahoma"), (FONTENUMPROC) EnumFontFamProc, 0) == 0) ? _T("Tahoma") : _T("Arial"); dc.DeleteDC(); } BEGIN_MESSAGE_MAP(CSizingControlBarCF, baseCSizingControlBarCF) //{{AFX_MSG_MAP(CSizingControlBarCF) //}}AFX_MSG_MAP ON_MESSAGE(WM_SETTEXT, OnSetText) END_MESSAGE_MAP() void CSizingControlBarCF::OnUpdateCmdUI(CFrameWnd* pTarget, BOOL bDisableIfNoHndler) { baseCSizingControlBarCF::OnUpdateCmdUI(pTarget, bDisableIfNoHndler); if (!HasGripper()) return; BOOL bNeedPaint = FALSE; CWnd* pFocus = GetFocus(); BOOL bActiveOld = m_bActive; m_bActive = (pFocus->GetSafeHwnd() && IsChild(pFocus)); if (m_bActive != bActiveOld) bNeedPaint = TRUE; if (bNeedPaint) SendMessage(WM_NCPAINT); } // gradient defines (if not already defined) #ifndef COLOR_GRADIENTACTIVECAPTION #define COLOR_GRADIENTACTIVECAPTION 27 #define COLOR_GRADIENTINACTIVECAPTION 28 #define SPI_GETGRADIENTCAPTIONS 0x1008 #endif void CSizingControlBarCF::NcPaintGripper(CDC* pDC, CRect rcClient) { if (!HasGripper()) return; // compute the caption rectangle BOOL bHorz = IsHorzDocked(); CRect rcGrip = rcClient; CRect rcBtn = m_biHide.GetRect(); if (bHorz) { // right side gripper rcGrip.left -= m_cyGripper + 1; rcGrip.right = rcGrip.left + 11; rcGrip.top = rcBtn.bottom + 3; } else { // gripper at top rcGrip.top -= m_cyGripper + 1; rcGrip.bottom = rcGrip.top + 11; rcGrip.right = rcBtn.left - 3; } rcGrip.InflateRect(bHorz ? 1 : 0, bHorz ? 0 : 1); // draw the caption background //CBrush br; COLORREF clrCptn = m_bActive ? ::GetSysColor(COLOR_ACTIVECAPTION) : ::GetSysColor(COLOR_INACTIVECAPTION); // query gradient info (usually TRUE for Win98/Win2k) BOOL bGradient = FALSE; ::SystemParametersInfo(SPI_GETGRADIENTCAPTIONS, 0, &bGradient, 0); if (!bGradient) pDC->FillSolidRect(&rcGrip, clrCptn); // solid color else { // gradient from left to right or from bottom to top // get second gradient color (the right end) COLORREF clrCptnRight = m_bActive ? ::GetSysColor(COLOR_GRADIENTACTIVECAPTION) : ::GetSysColor(COLOR_GRADIENTINACTIVECAPTION); // this will make 2^6 = 64 fountain steps int nShift = 6; int nSteps = 1 << nShift; for (int i = 0; i < nSteps; i++) { // do a little alpha blending int nR = (GetRValue(clrCptn) * (nSteps - i) + GetRValue(clrCptnRight) * i) >> nShift; int nG = (GetGValue(clrCptn) * (nSteps - i) + GetGValue(clrCptnRight) * i) >> nShift; int nB = (GetBValue(clrCptn) * (nSteps - i) + GetBValue(clrCptnRight) * i) >> nShift; COLORREF cr = RGB(nR, nG, nB); // then paint with the resulting color CRect r2 = rcGrip; if (bHorz) { r2.bottom = rcGrip.bottom - ((i * rcGrip.Height()) >> nShift); r2.top = rcGrip.bottom - (((i + 1) * rcGrip.Height()) >> nShift); if (r2.Height() > 0) pDC->FillSolidRect(r2, cr); } else { r2.left = rcGrip.left + ((i * rcGrip.Width()) >> nShift); r2.right = rcGrip.left + (((i + 1) * rcGrip.Width()) >> nShift); if (r2.Width() > 0) pDC->FillSolidRect(r2, cr); } } } // draw the caption text - first select a font CFont font; int ppi = pDC->GetDeviceCaps(LOGPIXELSX); int pointsize = MulDiv(85, 96, ppi); // 8.5 points at 96 ppi LOGFONT lf; BOOL bFont = font.CreatePointFont(pointsize, m_sFontFace); if (bFont) { // get the text color COLORREF clrCptnText = m_bActive ? ::GetSysColor(COLOR_CAPTIONTEXT) : ::GetSysColor(COLOR_INACTIVECAPTIONTEXT); int nOldBkMode = pDC->SetBkMode(TRANSPARENT); COLORREF clrOldText = pDC->SetTextColor(clrCptnText); if (bHorz) { // rotate text 90 degrees CCW if horizontally docked font.GetLogFont(&lf); font.DeleteObject(); lf.lfEscapement = 900; font.CreateFontIndirect(&lf); } CFont* pOldFont = pDC->SelectObject(&font); CString sTitle; GetWindowText(sTitle); CPoint ptOrg = bHorz ? CPoint(rcGrip.left - 1, rcGrip.bottom - 3) : CPoint(rcGrip.left + 3, rcGrip.top - 1); pDC->ExtTextOut(ptOrg.x, ptOrg.y, ETO_CLIPPED, rcGrip, sTitle, NULL); pDC->SelectObject(pOldFont); pDC->SetBkMode(nOldBkMode); pDC->SetTextColor(clrOldText); } // draw the button m_biHide.Paint(pDC); } LRESULT CSizingControlBarCF::OnSetText(WPARAM wParam, LPARAM lParam) { LRESULT lResult = baseCSizingControlBarCF::OnSetText(wParam, lParam); SendMessage(WM_NCPAINT); return lResult; }
zzh-project-test
branches/ThumbViewer/src/control_bar/scbarcf.cpp
C++
asf20
7,344
///////////////////////////////////////////////////////////////////////// // // CSizingControlBarCF Version 2.44 // // Created: Dec 21, 1998 Last Modified: March 31, 2002 // // See the official site at www.datamekanix.com for documentation and // the latest news. // ///////////////////////////////////////////////////////////////////////// // Copyright (C) 1998-2002 by Cristi Posea. All rights reserved. // // This code is free for personal and commercial use, providing this // notice remains intact in the source files and all eventual changes are // clearly marked with comments. // // You must obtain the author's consent before you can include this code // in a software library. // // No warrantee of any kind, express or implied, is included with this // software; use at your own risk, responsibility for damages (if any) to // anyone resulting from the use of this software rests entirely with the // user. // // Send bug reports, bug fixes, enhancements, requests, flames, etc. to // cristi@datamekanix.com or post them at the message board at the site. ///////////////////////////////////////////////////////////////////////// #if !defined(__SCBARCF_H__) #define __SCBARCF_H__ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 // scbarcf.h : header file // ///////////////////////////////////////////////////////////////////////// // CSizingControlBarCF #ifndef baseCSizingControlBarCF #define baseCSizingControlBarCF CSizingControlBarG #endif class CSizingControlBarCF : public baseCSizingControlBarCF { DECLARE_DYNAMIC(CSizingControlBarCF) // Construction public: CSizingControlBarCF(); // Overridables virtual void OnUpdateCmdUI(CFrameWnd* pTarget, BOOL bDisableIfNoHndler); // Implementation protected: // implementation helpers virtual void NcPaintGripper(CDC* pDC, CRect rcClient); protected: BOOL m_bActive; // a child has focus CString m_sFontFace; // Generated message map functions protected: //{{AFX_MSG(CSizingControlBarCF) //}}AFX_MSG afx_msg LRESULT OnSetText(WPARAM wParam, LPARAM lParam); DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////// #endif // !defined(__SCBARCF_H__)
zzh-project-test
branches/ThumbViewer/src/scbarcf.h
C++
asf20
2,316
#if !defined(AFX_DIRECTORYTREEBAR_H__BC4FAB7E_B856_46D4_A218_E427DCDF7117__INCLUDED_) #define AFX_DIRECTORYTREEBAR_H__BC4FAB7E_B856_46D4_A218_E427DCDF7117__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // DirectoryTreeBar.h : header file // #include "DirTreeCtrl.h" ///////////////////////////////////////////////////////////////////////////// // CDirectoryTreeBar window class CDirectoryTreeBar : public CSizingControlBarCF { // Construction public: CDirectoryTreeBar(); // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CDirectoryTreeBar) //}}AFX_VIRTUAL // Implementation public: virtual ~CDirectoryTreeBar(); // Generated message map functions protected: CDirTreeCtrl m_TreeCtrl; //{{AFX_MSG(CDirectoryTreeBar) afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnNcLButtonUp(UINT nHitTest, CPoint point); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_DIRECTORYTREEBAR_H__BC4FAB7E_B856_46D4_A218_E427DCDF7117__INCLUDED_)
zzh-project-test
branches/ThumbViewer/src/DirectoryTreeBar.h
C++
asf20
1,376
; CLW file contains information for the MFC ClassWizard [General Info] Version=1 LastClass=CThumbViewerView LastTemplate=CDialog NewFileInclude1=#include "stdafx.h" NewFileInclude2=#include "thumbviewer.h" LastPage=0 ClassCount=10 Class1=CDirectoryTreeBar Class2=CDirTreeCtrl Class3=CMainFrame Class4=CPreviewBar Class5=CThumbViewerApp Class6=CAboutDlg Class7=CThumbViewerDoc Class8=CThumbViewerView ResourceCount=2 Resource1=IDR_MAINFRAME (English (U.S.)) Class9=DlgListCtrl Class10=DlgCtrlListEx Resource2=IDD_ABOUTBOX (English (U.S.)) [CLS:CDirectoryTreeBar] Type=0 BaseClass=CSizingControlBarG HeaderFile=DirectoryTreeBar.h ImplementationFile=DirectoryTreeBar.cpp Filter=W VirtualFilter=WC LastObject=CDirectoryTreeBar [CLS:CDirTreeCtrl] Type=0 BaseClass=CTreeCtrl HeaderFile=DirTreeCtrl.h ImplementationFile=DirTreeCtrl.cpp [CLS:CMainFrame] Type=0 BaseClass=CFrameWnd HeaderFile=MainFrm.h ImplementationFile=MainFrm.cpp Filter=T VirtualFilter=fWC LastObject=ID_FILE_NEW [CLS:CPreviewBar] Type=0 BaseClass=CSizingControlBarG HeaderFile=PreviewBar.h ImplementationFile=PreviewBar.cpp Filter=W VirtualFilter=WC LastObject=CPreviewBar [CLS:CThumbViewerApp] Type=0 BaseClass=CWinApp HeaderFile=ThumbViewer.h ImplementationFile=ThumbViewer.cpp [CLS:CAboutDlg] Type=0 BaseClass=CDialog HeaderFile=ThumbViewer.cpp ImplementationFile=ThumbViewer.cpp LastObject=CAboutDlg [CLS:CThumbViewerDoc] Type=0 BaseClass=CDocument HeaderFile=ThumbViewerDoc.h ImplementationFile=ThumbViewerDoc.cpp LastObject=CThumbViewerDoc [CLS:CThumbViewerView] Type=0 BaseClass=CListView HeaderFile=ThumbViewerView.h ImplementationFile=ThumbViewerView.cpp Filter=C VirtualFilter=VWC LastObject=CThumbViewerView [DLG:IDD_ABOUTBOX] Type=1 Class=CAboutDlg [TB:IDR_MAINFRAME (English (U.S.))] Type=1 Class=? Command1=ID_FILE_NEW Command2=ID_STOP_THREAD Command3=ID_APP_ABOUT CommandCount=3 [MNU:IDR_MAINFRAME (English (U.S.))] Type=1 Class=CMainFrame Command1=ID_FILE_NEW Command2=ID_APP_EXIT Command3=ID_VIEW_TOOLBAR Command4=ID_VIEW_STATUS_BAR Command5=ID_VIEW_DIRECTORY_BAR Command6=ID_VIEW_PREVIEW_BAR Command7=ID_TEST Command8=ID_APP_ABOUT CommandCount=8 [ACL:IDR_MAINFRAME (English (U.S.))] Type=1 Class=? Command1=ID_FILE_NEW Command2=ID_FILE_OPEN Command3=ID_FILE_SAVE Command4=ID_FILE_PRINT Command5=ID_EDIT_UNDO Command6=ID_EDIT_CUT Command7=ID_EDIT_COPY Command8=ID_EDIT_PASTE Command9=ID_EDIT_UNDO Command10=ID_EDIT_CUT Command11=ID_EDIT_COPY Command12=ID_EDIT_PASTE Command13=ID_NEXT_PANE Command14=ID_PREV_PANE CommandCount=14 [DLG:IDD_ABOUTBOX (English (U.S.))] Type=1 Class=? ControlCount=4 Control1=IDC_STATIC,static,1342177283 Control2=IDC_STATIC,static,1342308480 Control3=IDC_STATIC,static,1342308352 Control4=IDOK,button,1342373889 [CLS:DlgListCtrl] Type=0 HeaderFile=DlgListCtrl.h ImplementationFile=DlgListCtrl.cpp BaseClass=CDialog Filter=D VirtualFilter=dWC LastObject=DlgListCtrl [CLS:DlgCtrlListEx] Type=0 HeaderFile=DlgCtrlListEx.h ImplementationFile=DlgCtrlListEx.cpp BaseClass=CDialog Filter=D LastObject=ID_TEST
zzh-project-test
branches/ThumbViewer/src/ThumbViewer.clw
Clarion
asf20
3,187
#pragma once #include "ButtonEx.h" #include <map> using namespace std; // #include <vector> // typedef vector<CButtonEx*> vpButton; typedef map<int,CButtonEx*>button_map; // CListCtrlEx class CListCtrlEx : public CListView//CListCtrl { DECLARE_DYNAMIC(CListCtrlEx) public: CListCtrlEx(); virtual ~CListCtrlEx(); protected: // DECLARE_MESSAGE_MAP() public: void createItemButton( int nItem, int nSubItem, HWND hMain,CRect re,CString str="" ); void release(); void deleteItemEx( int nItem ); button_map m_mButton; void deleteItemButton( int nItem ); CButtonEx* m_btn; int m_nButtonNum; int init(int n); int repaint(); int deletall(); public: UINT m_uID; //void updateListCtrlButtonPos(); //void enableButton( BOOL bFlag, int iItem ); };
zzh-project-test
branches/ThumbViewer/src/ListCtrlEx.h
C++
asf20
816
// DlgListCtrl.cpp : implementation file // #include "stdafx.h" #include "thumbviewer.h" #include "DlgListCtrl.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // DlgListCtrl dialog DlgListCtrl::DlgListCtrl(CWnd* pParent /*=NULL*/) : CDialog(DlgListCtrl::IDD, pParent) { //{{AFX_DATA_INIT(DlgListCtrl) //}}AFX_DATA_INIT } void DlgListCtrl::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(DlgListCtrl) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(DlgListCtrl, CDialog) //{{AFX_MSG_MAP(DlgListCtrl) // NOTE: the ClassWizard will add message map macros here //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // DlgListCtrl message handlers
zzh-project-test
branches/ThumbViewer/src/DlgListCtrl.cpp
C++
asf20
916
#pragma once // CButtonEx class CButtonEx : public CButton { DECLARE_DYNAMIC(CButtonEx) public: CButtonEx(); CButtonEx( int nItem, int nSubItem, CRect rect, HWND hParent,CString str ); int SetParam(int nItem, int nSubItem, CRect rect, HWND hParent,CString str); // CButtonEx& operator = (const CButtonEx& other); virtual ~CButtonEx(); protected: DECLARE_MESSAGE_MAP() public: afx_msg void OnBnClicked(); int m_inItem; int m_inSubItem; CRect m_rect; HWND m_hParent; BOOL bEnable; CString m_strFileName; };
zzh-project-test
branches/ThumbViewer/src/ButtonEx.h
C++
asf20
558
#ifndef _CPROTIMER_H_ #define _CPROTIMER_H_ #include "windows.h" // // CProTimer Class Declaration // class CProTimer { public: CProTimer(); void Reset(); float GetTime(bool reset); protected: LONGLONG m_CounterFrequency; LONGLONG m_ResetTime; }; #endif // _CPROTIMER_H_
zzh-project-test
branches/ThumbViewer/src/CProTimer.h
C++
asf20
305
///////////////////////////////////////////////////////////////////////// // // CSizingControlBar Version 2.44 // // Created: Jan 24, 1998 Last Modified: March 31, 2002 // // See the official site at www.datamekanix.com for documentation and // the latest news. // ///////////////////////////////////////////////////////////////////////// // Copyright (C) 1998-2002 by Cristi Posea. All rights reserved. // // This code is free for personal and commercial use, providing this // notice remains intact in the source files and all eventual changes are // clearly marked with comments. // // You must obtain the author's consent before you can include this code // in a software library. // // No warrantee of any kind, express or implied, is included with this // software; use at your own risk, responsibility for damages (if any) to // anyone resulting from the use of this software rests entirely with the // user. // // Send bug reports, bug fixes, enhancements, requests, flames, etc. to // cristi@datamekanix.com or post them at the message board at the site. // // The sources and a short version of the docs are also available at // www.codeproject.com . Look for a "Docking Windows" section and check // the version to be sure you get the latest one ;) // // Hint: These classes are intended to be used as base classes. Do not // simply add your code to these files - instead create a new class // derived from one of CSizingControlBarXX classes and put there what // you need. See CMyBar classes in the demo projects for examples. // Modify this file only to fix bugs, and don't forget to send me a copy. ///////////////////////////////////////////////////////////////////////// // Acknowledgements: // o Thanks to Harlan R. Seymour for his continuous support during // development of this code. // o Thanks to Dundas Software for the opportunity // to test this code on real-life applications. // o Some ideas for the gripper came from the CToolBarEx flat toolbar // by Joerg Koenig. Thanks, Joerg! // o Thanks to Robert Wolpow for the code on which CDockContext based // dialgonal resizing is based. // o Thanks to the following people for various bug fixes and/or // enhancements: Chris Maunder, Jakawan Ratiwanich, Udo Schaefer, // Anatoly Ivasyuk, Peter Hauptmann, DJ(?), Pat Kusbel, Aleksey // Malyshev. // o And, of course, many thanks to all of you who used this code, // for the invaluable feedback I received. ///////////////////////////////////////////////////////////////////////// // sizecbar.cpp : implementation file // //#include "stdafx.h" #include "StdAfx.h" #include "sizecbar.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////// // CSizingControlBar IMPLEMENT_DYNAMIC(CSizingControlBar, baseCSizingControlBar); CSizingControlBar::CSizingControlBar() { m_szMinHorz = CSize(33, 32); m_szMinVert = CSize(33, 32); m_szMinFloat = CSize(37, 32); m_szHorz = CSize(200, 200); m_szVert = CSize(200, 200); m_szFloat = CSize(200, 200); m_bTracking = FALSE; m_bKeepSize = FALSE; m_bParentSizing = FALSE; m_cxEdge = 5; m_bDragShowContent = FALSE; m_nDockBarID = 0; m_dwSCBStyle = 0; } CSizingControlBar::~CSizingControlBar() { } BEGIN_MESSAGE_MAP(CSizingControlBar, baseCSizingControlBar) //{{AFX_MSG_MAP(CSizingControlBar) ON_WM_CREATE() ON_WM_PAINT() ON_WM_NCPAINT() ON_WM_NCCALCSIZE() ON_WM_WINDOWPOSCHANGING() ON_WM_CAPTURECHANGED() ON_WM_SETTINGCHANGE() ON_WM_LBUTTONUP() ON_WM_MOUSEMOVE() ON_WM_NCLBUTTONDOWN() ON_WM_LBUTTONDOWN() ON_WM_LBUTTONDBLCLK() ON_WM_RBUTTONDOWN() ON_WM_NCMOUSEMOVE() ON_WM_NCHITTEST() ON_WM_CLOSE() ON_WM_SIZE() //}}AFX_MSG_MAP ON_MESSAGE(WM_SETTEXT, OnSetText) END_MESSAGE_MAP() // old creation method, still here for compatibility reasons BOOL CSizingControlBar::Create(LPCTSTR lpszWindowName, CWnd* pParentWnd, CSize sizeDefault, BOOL bHasGripper, UINT nID, DWORD dwStyle) { UNUSED_ALWAYS(bHasGripper); m_szHorz = m_szVert = m_szFloat = sizeDefault; return Create(lpszWindowName, pParentWnd, nID, dwStyle); } // preffered creation method BOOL CSizingControlBar::Create(LPCTSTR lpszWindowName, CWnd* pParentWnd, UINT nID, DWORD dwStyle) { // must have a parent ASSERT_VALID(pParentWnd); // cannot be both fixed and dynamic // (CBRS_SIZE_DYNAMIC is used for resizng when floating) ASSERT (!((dwStyle & CBRS_SIZE_FIXED) && (dwStyle & CBRS_SIZE_DYNAMIC))); m_dwStyle = dwStyle & CBRS_ALL; // save the control bar styles // register and create the window - skip CControlBar::Create() CString wndclass = ::AfxRegisterWndClass(CS_DBLCLKS, ::LoadCursor(NULL, IDC_ARROW), ::GetSysColorBrush(COLOR_BTNFACE), 0); dwStyle &= ~CBRS_ALL; // keep only the generic window styles dwStyle |= WS_CLIPCHILDREN; // prevents flashing if (!CWnd::Create(wndclass, lpszWindowName, dwStyle, CRect(0, 0, 0, 0), pParentWnd, nID)) return FALSE; return TRUE; } ///////////////////////////////////////////////////////////////////////// // CSizingControlBar operations #if defined(_SCB_REPLACE_MINIFRAME) && !defined(_SCB_MINIFRAME_CAPTION) void CSizingControlBar::EnableDocking(DWORD dwDockStyle) { // must be CBRS_ALIGN_XXX or CBRS_FLOAT_MULTI only ASSERT((dwDockStyle & ~(CBRS_ALIGN_ANY|CBRS_FLOAT_MULTI)) == 0); // cannot have the CBRS_FLOAT_MULTI style ASSERT((dwDockStyle & CBRS_FLOAT_MULTI) == 0); // the bar must have CBRS_SIZE_DYNAMIC style ASSERT((m_dwStyle & CBRS_SIZE_DYNAMIC) != 0); m_dwDockStyle = dwDockStyle; if (m_pDockContext == NULL) m_pDockContext = new CSCBDockContext(this); // permanently wire the bar's owner to its current parent if (m_hWndOwner == NULL) m_hWndOwner = ::GetParent(m_hWnd); } #endif ///////////////////////////////////////////////////////////////////////// // CSizingControlBar message handlers int CSizingControlBar::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (baseCSizingControlBar::OnCreate(lpCreateStruct) == -1) return -1; // query SPI_GETDRAGFULLWINDOWS system parameter // OnSettingChange() will update m_bDragShowContent m_bDragShowContent = FALSE; ::SystemParametersInfo(SPI_GETDRAGFULLWINDOWS, 0, &m_bDragShowContent, 0); // uncomment this line if you want raised borders // m_dwSCBStyle |= SCBS_SHOWEDGES; return 0; } LRESULT CSizingControlBar::OnSetText(WPARAM wParam, LPARAM lParam) { UNUSED_ALWAYS(wParam); LRESULT lResult = CWnd::Default(); if (IsFloating() && GetParentFrame()->IsKindOf(RUNTIME_CLASS(CMiniDockFrameWnd))) { m_pDockBar->SetWindowText((LPCTSTR) lParam); // update dockbar GetParentFrame()->DelayRecalcLayout(); // refresh miniframe } return lResult; } const BOOL CSizingControlBar::IsFloating() const { return !IsHorzDocked() && !IsVertDocked(); } const BOOL CSizingControlBar::IsHorzDocked() const { return (m_nDockBarID == AFX_IDW_DOCKBAR_TOP || m_nDockBarID == AFX_IDW_DOCKBAR_BOTTOM); } const BOOL CSizingControlBar::IsVertDocked() const { return (m_nDockBarID == AFX_IDW_DOCKBAR_LEFT || m_nDockBarID == AFX_IDW_DOCKBAR_RIGHT); } const BOOL CSizingControlBar::IsSideTracking() const { // don't call this when not tracking ASSERT(m_bTracking && !IsFloating()); return (m_htEdge == HTLEFT || m_htEdge == HTRIGHT) ? IsHorzDocked() : IsVertDocked(); } CSize CSizingControlBar::CalcFixedLayout(BOOL bStretch, BOOL bHorz) { if (bStretch) // the bar is stretched (is not the child of a dockbar) if (bHorz) return CSize(32767, m_szHorz.cy); else return CSize(m_szVert.cx, 32767); // dirty cast - we need access to protected CDockBar members CSCBDockBar* pDockBar = (CSCBDockBar*) m_pDockBar; // force imediate RecalcDelayShow() for all sizing bars on the row // with delayShow/delayHide flags set to avoid IsVisible() problems CSCBArray arrSCBars; GetRowSizingBars(arrSCBars); AFX_SIZEPARENTPARAMS layout; layout.hDWP = pDockBar->m_bLayoutQuery ? NULL : ::BeginDeferWindowPos(arrSCBars.GetSize()); for (int i = 0; i < arrSCBars.GetSize(); i++) if (arrSCBars[i]->m_nStateFlags & (delayHide|delayShow)) arrSCBars[i]->RecalcDelayShow(&layout); if (layout.hDWP != NULL) ::EndDeferWindowPos(layout.hDWP); // get available length CRect rc = pDockBar->m_rectLayout; if (rc.IsRectEmpty()) m_pDockSite->GetClientRect(&rc); int nLengthTotal = bHorz ? rc.Width() + 2 : rc.Height() - 2; if (IsVisible() && !IsFloating() && m_bParentSizing && arrSCBars[0] == this) if (NegotiateSpace(nLengthTotal, (bHorz != FALSE))) AlignControlBars(); m_bParentSizing = FALSE; if (bHorz) return CSize(max(m_szMinHorz.cx, m_szHorz.cx), max(m_szMinHorz.cy, m_szHorz.cy)); return CSize(max(m_szMinVert.cx, m_szVert.cx), max(m_szMinVert.cy, m_szVert.cy)); } CSize CSizingControlBar::CalcDynamicLayout(int nLength, DWORD dwMode) { if (dwMode & (LM_HORZDOCK | LM_VERTDOCK)) // docked ? { if (nLength == -1) m_bParentSizing = TRUE; return baseCSizingControlBar::CalcDynamicLayout(nLength, dwMode); } if (dwMode & LM_MRUWIDTH) return m_szFloat; if (dwMode & LM_COMMIT) return m_szFloat; // already committed #ifndef _SCB_REPLACE_MINIFRAME // check for dialgonal resizing hit test int nHitTest = m_pDockContext->m_nHitTest; if (IsFloating() && (nHitTest == HTTOPLEFT || nHitTest == HTBOTTOMLEFT || nHitTest == HTTOPRIGHT || nHitTest == HTBOTTOMRIGHT)) { CPoint ptCursor; ::GetCursorPos(&ptCursor); CRect rFrame, rBar; GetParentFrame()->GetWindowRect(&rFrame); GetWindowRect(&rBar); if (nHitTest == HTTOPLEFT || nHitTest == HTBOTTOMLEFT) { m_szFloat.cx = rFrame.left + rBar.Width() - ptCursor.x; m_pDockContext->m_rectFrameDragHorz.left = min(ptCursor.x, rFrame.left + rBar.Width() - m_szMinFloat.cx); } if (nHitTest == HTTOPLEFT || nHitTest == HTTOPRIGHT) { m_szFloat.cy = rFrame.top + rBar.Height() - ptCursor.y; m_pDockContext->m_rectFrameDragHorz.top = min(ptCursor.y, rFrame.top + rBar.Height() - m_szMinFloat.cy); } if (nHitTest == HTTOPRIGHT || nHitTest == HTBOTTOMRIGHT) m_szFloat.cx = rBar.Width() + ptCursor.x - rFrame.right; if (nHitTest == HTBOTTOMLEFT || nHitTest == HTBOTTOMRIGHT) m_szFloat.cy = rBar.Height() + ptCursor.y - rFrame.bottom; } else #endif //_SCB_REPLACE_MINIFRAME ((dwMode & LM_LENGTHY) ? m_szFloat.cy : m_szFloat.cx) = nLength; m_szFloat.cx = max(m_szFloat.cx, m_szMinFloat.cx); m_szFloat.cy = max(m_szFloat.cy, m_szMinFloat.cy); return m_szFloat; } void CSizingControlBar::OnWindowPosChanging(WINDOWPOS FAR* lpwndpos) { // force non-client recalc if moved or resized lpwndpos->flags |= SWP_FRAMECHANGED; baseCSizingControlBar::OnWindowPosChanging(lpwndpos); // find on which side are we docked m_nDockBarID = GetParent()->GetDlgCtrlID(); if (!IsFloating()) if (lpwndpos->flags & SWP_SHOWWINDOW) m_bKeepSize = TRUE; } ///////////////////////////////////////////////////////////////////////// // Mouse Handling // void CSizingControlBar::OnLButtonDown(UINT nFlags, CPoint point) { if (m_pDockBar != NULL) { // start the drag ASSERT(m_pDockContext != NULL); ClientToScreen(&point); m_pDockContext->StartDrag(point); } else CWnd::OnLButtonDown(nFlags, point); } void CSizingControlBar::OnLButtonDblClk(UINT nFlags, CPoint point) { if (m_pDockBar != NULL) { // toggle docking ASSERT(m_pDockContext != NULL); m_pDockContext->ToggleDocking(); } else CWnd::OnLButtonDblClk(nFlags, point); } void CSizingControlBar::OnNcLButtonDown(UINT nHitTest, CPoint point) { UNUSED_ALWAYS(point); if (m_bTracking || IsFloating()) return; if ((nHitTest >= HTSIZEFIRST) && (nHitTest <= HTSIZELAST)) StartTracking(nHitTest, point); // sizing edge hit } void CSizingControlBar::OnLButtonUp(UINT nFlags, CPoint point) { if (m_bTracking) StopTracking(); baseCSizingControlBar::OnLButtonUp(nFlags, point); } void CSizingControlBar::OnRButtonDown(UINT nFlags, CPoint point) { if (m_bTracking) StopTracking(); baseCSizingControlBar::OnRButtonDown(nFlags, point); } void CSizingControlBar::OnMouseMove(UINT nFlags, CPoint point) { if (m_bTracking) { CPoint ptScreen = point; ClientToScreen(&ptScreen); OnTrackUpdateSize(ptScreen); } baseCSizingControlBar::OnMouseMove(nFlags, point); } void CSizingControlBar::OnCaptureChanged(CWnd *pWnd) { if (m_bTracking && (pWnd != this)) StopTracking(); baseCSizingControlBar::OnCaptureChanged(pWnd); } void CSizingControlBar::OnNcCalcSize(BOOL bCalcValidRects, NCCALCSIZE_PARAMS FAR* lpncsp) { UNUSED_ALWAYS(bCalcValidRects); #ifndef _SCB_REPLACE_MINIFRAME // Enable diagonal resizing for floating miniframe if (IsFloating()) { CFrameWnd* pFrame = GetParentFrame(); if (pFrame != NULL && pFrame->IsKindOf(RUNTIME_CLASS(CMiniFrameWnd))) { DWORD dwStyle = ::GetWindowLong(pFrame->m_hWnd, GWL_STYLE); if ((dwStyle & MFS_4THICKFRAME) != 0) { pFrame->ModifyStyle(MFS_4THICKFRAME, 0); // clear GetParent()->ModifyStyle(0, WS_CLIPCHILDREN); } } } #endif _SCB_REPLACE_MINIFRAME // compute the the client area m_dwSCBStyle &= ~SCBS_EDGEALL; // add resizing edges between bars on the same row if (!IsFloating() && m_pDockBar != NULL) { CSCBArray arrSCBars; int nThis; GetRowSizingBars(arrSCBars, nThis); BOOL bHorz = IsHorzDocked(); if (nThis > 0) m_dwSCBStyle |= bHorz ? SCBS_EDGELEFT : SCBS_EDGETOP; if (nThis < arrSCBars.GetUpperBound()) m_dwSCBStyle |= bHorz ? SCBS_EDGERIGHT : SCBS_EDGEBOTTOM; } NcCalcClient(&lpncsp->rgrc[0], m_nDockBarID); } void CSizingControlBar::NcCalcClient(LPRECT pRc, UINT nDockBarID) { CRect rc(pRc); rc.DeflateRect(3, 5, 3, 3); if (nDockBarID != AFX_IDW_DOCKBAR_FLOAT) rc.DeflateRect(2, 0, 2, 2); switch(nDockBarID) { case AFX_IDW_DOCKBAR_TOP: m_dwSCBStyle |= SCBS_EDGEBOTTOM; break; case AFX_IDW_DOCKBAR_BOTTOM: m_dwSCBStyle |= SCBS_EDGETOP; break; case AFX_IDW_DOCKBAR_LEFT: m_dwSCBStyle |= SCBS_EDGERIGHT; break; case AFX_IDW_DOCKBAR_RIGHT: m_dwSCBStyle |= SCBS_EDGELEFT; break; } // make room for edges only if they will be painted if (m_dwSCBStyle & SCBS_SHOWEDGES) rc.DeflateRect( (m_dwSCBStyle & SCBS_EDGELEFT) ? m_cxEdge : 0, (m_dwSCBStyle & SCBS_EDGETOP) ? m_cxEdge : 0, (m_dwSCBStyle & SCBS_EDGERIGHT) ? m_cxEdge : 0, (m_dwSCBStyle & SCBS_EDGEBOTTOM) ? m_cxEdge : 0); *pRc = rc; } void CSizingControlBar::OnNcPaint() { // get window DC that is clipped to the non-client area CWindowDC dc(this); // the HDC will be released by the destructor CRect rcClient, rcBar; GetClientRect(rcClient); ClientToScreen(rcClient); GetWindowRect(rcBar); rcClient.OffsetRect(-rcBar.TopLeft()); rcBar.OffsetRect(-rcBar.TopLeft()); CDC mdc; mdc.CreateCompatibleDC(&dc); CBitmap bm; bm.CreateCompatibleBitmap(&dc, rcBar.Width(), rcBar.Height()); CBitmap* pOldBm = mdc.SelectObject(&bm); // draw borders in non-client area CRect rcDraw = rcBar; DrawBorders(&mdc, rcDraw); // erase the NC background mdc.FillRect(rcDraw, CBrush::FromHandle( (HBRUSH) GetClassLong(m_hWnd, GCL_HBRBACKGROUND))); if (m_dwSCBStyle & SCBS_SHOWEDGES) { CRect rcEdge; // paint the sizing edges for (int i = 0; i < 4; i++) if (GetEdgeRect(rcBar, GetEdgeHTCode(i), rcEdge)) mdc.Draw3dRect(rcEdge, ::GetSysColor(COLOR_BTNHIGHLIGHT), ::GetSysColor(COLOR_BTNSHADOW)); } NcPaintGripper(&mdc, rcClient); // client area is not our bussiness :) dc.IntersectClipRect(rcBar); dc.ExcludeClipRect(rcClient); dc.BitBlt(0, 0, rcBar.Width(), rcBar.Height(), &mdc, 0, 0, SRCCOPY); mdc.SelectObject(pOldBm); bm.DeleteObject(); mdc.DeleteDC(); } void CSizingControlBar::NcPaintGripper(CDC* pDC, CRect rcClient) { UNUSED_ALWAYS(pDC); UNUSED_ALWAYS(rcClient); } void CSizingControlBar::OnPaint() { // overridden to skip border painting based on clientrect CPaintDC dc(this); } //UINT CSizingControlBar::OnNcHitTest(CPoint point) LRESULT CSizingControlBar::OnNcHitTest(CPoint point) { CRect rcBar, rcEdge; GetWindowRect(rcBar); if (!IsFloating()) for (int i = 0; i < 4; i++) if (GetEdgeRect(rcBar, GetEdgeHTCode(i), rcEdge)) if (rcEdge.PtInRect(point)) return GetEdgeHTCode(i); return HTCLIENT; } void CSizingControlBar::OnSettingChange(UINT uFlags, LPCTSTR lpszSection) { baseCSizingControlBar::OnSettingChange(uFlags, lpszSection); m_bDragShowContent = FALSE; ::SystemParametersInfo(SPI_GETDRAGFULLWINDOWS, 0, &m_bDragShowContent, 0); // update } void CSizingControlBar::OnSize(UINT nType, int cx, int cy) { UNUSED_ALWAYS(nType); if ((m_dwSCBStyle & SCBS_SIZECHILD) != 0) { // automatic child resizing - only one child is allowed CWnd* pWnd = GetWindow(GW_CHILD); if (pWnd != NULL) { pWnd->MoveWindow(0, 0, cx, cy); ASSERT(pWnd->GetWindow(GW_HWNDNEXT) == NULL); } } } void CSizingControlBar::OnClose() { // do nothing: protection against accidentally destruction by the // child control (i.e. if user hits Esc in a child editctrl) } ///////////////////////////////////////////////////////////////////////// // CSizingControlBar implementation helpers void CSizingControlBar::StartTracking(UINT nHitTest, CPoint point) { SetCapture(); // make sure no updates are pending if (!m_bDragShowContent) RedrawWindow(NULL, NULL, RDW_ALLCHILDREN | RDW_UPDATENOW); m_htEdge = nHitTest; m_bTracking = TRUE; BOOL bHorz = IsHorzDocked(); BOOL bHorzTracking = m_htEdge == HTLEFT || m_htEdge == HTRIGHT; m_nTrackPosOld = bHorzTracking ? point.x : point.y; CRect rcBar, rcEdge; GetWindowRect(rcBar); GetEdgeRect(rcBar, m_htEdge, rcEdge); m_nTrackEdgeOfs = m_nTrackPosOld - (bHorzTracking ? rcEdge.CenterPoint().x : rcEdge.CenterPoint().y); CSCBArray arrSCBars; int nThis; GetRowSizingBars(arrSCBars, nThis); m_nTrackPosMin = m_nTrackPosMax = m_nTrackPosOld; if (!IsSideTracking()) { // calc minwidth as the max minwidth of the sizing bars on row int nMinWidth = bHorz ? m_szMinHorz.cy : m_szMinVert.cx; for (int i = 0; i < arrSCBars.GetSize(); i++) nMinWidth = max(nMinWidth, bHorz ? arrSCBars[i]->m_szMinHorz.cy : arrSCBars[i]->m_szMinVert.cx); int nExcessWidth = (bHorz ? m_szHorz.cy : m_szVert.cx) - nMinWidth; // the control bar cannot grow with more than the width of // remaining client area of the mainframe CRect rcT; m_pDockSite->RepositionBars(0, 0xFFFF, AFX_IDW_PANE_FIRST, reposQuery, &rcT, NULL, TRUE); int nMaxWidth = bHorz ? rcT.Height() - 2 : rcT.Width() - 2; BOOL bTopOrLeft = m_htEdge == HTTOP || m_htEdge == HTLEFT; m_nTrackPosMin -= bTopOrLeft ? nMaxWidth : nExcessWidth; m_nTrackPosMax += bTopOrLeft ? nExcessWidth : nMaxWidth; } else { // side tracking: // max size is the actual size plus the amount the other // sizing bars can be decreased until they reach their minsize if (m_htEdge == HTBOTTOM || m_htEdge == HTRIGHT) nThis++; for (int i = 0; i < arrSCBars.GetSize(); i++) { CSizingControlBar* pBar = arrSCBars[i]; int nExcessWidth = bHorz ? pBar->m_szHorz.cx - pBar->m_szMinHorz.cx : pBar->m_szVert.cy - pBar->m_szMinVert.cy; if (i < nThis) m_nTrackPosMin -= nExcessWidth; else m_nTrackPosMax += nExcessWidth; } } OnTrackInvertTracker(); // draw tracker } void CSizingControlBar::StopTracking() { OnTrackInvertTracker(); // erase tracker m_bTracking = FALSE; ReleaseCapture(); m_pDockSite->DelayRecalcLayout(); } void CSizingControlBar::OnTrackUpdateSize(CPoint& point) { ASSERT(!IsFloating()); BOOL bHorzTrack = m_htEdge == HTLEFT || m_htEdge == HTRIGHT; int nTrackPos = bHorzTrack ? point.x : point.y; nTrackPos = max(m_nTrackPosMin, min(m_nTrackPosMax, nTrackPos)); int nDelta = nTrackPos - m_nTrackPosOld; if (nDelta == 0) return; // no pos change OnTrackInvertTracker(); // erase tracker m_nTrackPosOld = nTrackPos; BOOL bHorz = IsHorzDocked(); CSize sizeNew = bHorz ? m_szHorz : m_szVert; switch (m_htEdge) { case HTLEFT: sizeNew -= CSize(nDelta, 0); break; case HTTOP: sizeNew -= CSize(0, nDelta); break; case HTRIGHT: sizeNew += CSize(nDelta, 0); break; case HTBOTTOM: sizeNew += CSize(0, nDelta); break; } CSCBArray arrSCBars; int nThis; GetRowSizingBars(arrSCBars, nThis); if (!IsSideTracking()) for (int i = 0; i < arrSCBars.GetSize(); i++) { CSizingControlBar* pBar = arrSCBars[i]; // make same width (or height) (bHorz ? pBar->m_szHorz.cy : pBar->m_szVert.cx) = bHorz ? sizeNew.cy : sizeNew.cx; } else { int nGrowingBar = nThis; BOOL bBefore = m_htEdge == HTTOP || m_htEdge == HTLEFT; if (bBefore && nDelta > 0) nGrowingBar--; if (!bBefore && nDelta < 0) nGrowingBar++; if (nGrowingBar != nThis) bBefore = !bBefore; // nGrowing is growing nDelta = abs(nDelta); CSizingControlBar* pBar = arrSCBars[nGrowingBar]; (bHorz ? pBar->m_szHorz.cx : pBar->m_szVert.cy) += nDelta; // the others are shrinking int nFirst = bBefore ? nGrowingBar - 1 : nGrowingBar + 1; int nLimit = bBefore ? -1 : arrSCBars.GetSize(); for (int i = nFirst; nDelta != 0 && i != nLimit; i += (bBefore ? -1 : 1)) { CSizingControlBar* pBar = arrSCBars[i]; int nDeltaT = min(nDelta, (bHorz ? pBar->m_szHorz.cx : pBar->m_szVert.cy) - (bHorz ? pBar->m_szMinHorz.cx : pBar->m_szMinVert.cy)); (bHorz ? pBar->m_szHorz.cx : pBar->m_szVert.cy) -= nDeltaT; nDelta -= nDeltaT; } } OnTrackInvertTracker(); // redraw tracker at new pos if (m_bDragShowContent) m_pDockSite->DelayRecalcLayout(); } void CSizingControlBar::OnTrackInvertTracker() { ASSERT(m_bTracking); if (m_bDragShowContent) return; // don't show tracker if DragFullWindows is on BOOL bHorz = IsHorzDocked(); CRect rc, rcBar, rcDock, rcFrame; GetWindowRect(rcBar); m_pDockBar->GetWindowRect(rcDock); m_pDockSite->GetWindowRect(rcFrame); VERIFY(GetEdgeRect(rcBar, m_htEdge, rc)); if (!IsSideTracking()) rc = bHorz ? CRect(rcDock.left + 1, rc.top, rcDock.right - 1, rc.bottom) : CRect(rc.left, rcDock.top + 1, rc.right, rcDock.bottom - 1); BOOL bHorzTracking = m_htEdge == HTLEFT || m_htEdge == HTRIGHT; int nOfs = m_nTrackPosOld - m_nTrackEdgeOfs; nOfs -= bHorzTracking ? rc.CenterPoint().x : rc.CenterPoint().y; rc.OffsetRect(bHorzTracking ? nOfs : 0, bHorzTracking ? 0 : nOfs); rc.OffsetRect(-rcFrame.TopLeft()); CDC *pDC = m_pDockSite->GetDCEx(NULL, DCX_WINDOW | DCX_CACHE | DCX_LOCKWINDOWUPDATE); CBrush* pBrush = CDC::GetHalftoneBrush(); CBrush* pBrushOld = pDC->SelectObject(pBrush); pDC->PatBlt(rc.left, rc.top, rc.Width(), rc.Height(), PATINVERT); pDC->SelectObject(pBrushOld); m_pDockSite->ReleaseDC(pDC); } BOOL CSizingControlBar::GetEdgeRect(CRect rcWnd, UINT nHitTest, CRect& rcEdge) { rcEdge = rcWnd; if (m_dwSCBStyle & SCBS_SHOWEDGES) rcEdge.DeflateRect(1, 1); BOOL bHorz = IsHorzDocked(); switch (nHitTest) { case HTLEFT: if (!(m_dwSCBStyle & SCBS_EDGELEFT)) return FALSE; rcEdge.right = rcEdge.left + m_cxEdge; rcEdge.DeflateRect(0, bHorz ? m_cxEdge: 0); break; case HTTOP: if (!(m_dwSCBStyle & SCBS_EDGETOP)) return FALSE; rcEdge.bottom = rcEdge.top + m_cxEdge; rcEdge.DeflateRect(bHorz ? 0 : m_cxEdge, 0); break; case HTRIGHT: if (!(m_dwSCBStyle & SCBS_EDGERIGHT)) return FALSE; rcEdge.left = rcEdge.right - m_cxEdge; rcEdge.DeflateRect(0, bHorz ? m_cxEdge: 0); break; case HTBOTTOM: if (!(m_dwSCBStyle & SCBS_EDGEBOTTOM)) return FALSE; rcEdge.top = rcEdge.bottom - m_cxEdge; rcEdge.DeflateRect(bHorz ? 0 : m_cxEdge, 0); break; default: ASSERT(FALSE); // invalid hit test code } return TRUE; } UINT CSizingControlBar::GetEdgeHTCode(int nEdge) { if (nEdge == 0) return HTLEFT; if (nEdge == 1) return HTTOP; if (nEdge == 2) return HTRIGHT; if (nEdge == 3) return HTBOTTOM; ASSERT(FALSE); // invalid edge code return HTNOWHERE; } void CSizingControlBar::GetRowInfo(int& nFirst, int& nLast, int& nThis) { ASSERT_VALID(m_pDockBar); // verify bounds nThis = m_pDockBar->FindBar(this); ASSERT(nThis != -1); int i, nBars = m_pDockBar->m_arrBars.GetSize(); // find the first and the last bar in row for (nFirst = -1, i = nThis - 1; i >= 0 && nFirst == -1; i--) if (m_pDockBar->m_arrBars[i] == NULL) nFirst = i + 1; for (nLast = -1, i = nThis + 1; i < nBars && nLast == -1; i++) if (m_pDockBar->m_arrBars[i] == NULL) nLast = i - 1; ASSERT((nLast != -1) && (nFirst != -1)); } void CSizingControlBar::GetRowSizingBars(CSCBArray& arrSCBars) { int nThis; // dummy GetRowSizingBars(arrSCBars, nThis); } void CSizingControlBar::GetRowSizingBars(CSCBArray& arrSCBars, int& nThis) { arrSCBars.RemoveAll(); int nFirstT, nLastT, nThisT; GetRowInfo(nFirstT, nLastT, nThisT); nThis = -1; for (int i = nFirstT; i <= nLastT; i++) { CSizingControlBar* pBar = (CSizingControlBar*) m_pDockBar->m_arrBars[i]; if (HIWORD(pBar) == 0) continue; // placeholder if (!pBar->IsVisible()) continue; if (pBar->IsKindOf(RUNTIME_CLASS(CSizingControlBar))) { if (pBar == this) nThis = arrSCBars.GetSize(); arrSCBars.Add(pBar); } } } BOOL CSizingControlBar::NegotiateSpace(int nLengthTotal, BOOL bHorz) { ASSERT(bHorz == IsHorzDocked()); int nFirst, nLast, nThis; GetRowInfo(nFirst, nLast, nThis); int nLengthAvail = nLengthTotal; int nLengthActual = 0; int nLengthMin = 2; int nWidthMax = 0; CSizingControlBar* pBar; int i; for (i = nFirst; i <= nLast; i++) { pBar = (CSizingControlBar*) m_pDockBar->m_arrBars[i]; if (HIWORD(pBar) == 0) continue; // placeholder if (!pBar->IsVisible()) continue; BOOL bIsSizingBar = pBar->IsKindOf(RUNTIME_CLASS(CSizingControlBar)); int nLengthBar; // minimum length of the bar if (bIsSizingBar) nLengthBar = bHorz ? pBar->m_szMinHorz.cx - 2 : pBar->m_szMinVert.cy - 2; else { CRect rcBar; pBar->GetWindowRect(&rcBar); nLengthBar = bHorz ? rcBar.Width() - 2 : rcBar.Height() - 2; } nLengthMin += nLengthBar; if (nLengthMin > nLengthTotal) { // split the row after fixed bar if (i < nThis) { m_pDockBar->m_arrBars.InsertAt(i + 1, (CControlBar*) NULL); return FALSE; } // only this sizebar remains on the row, adjust it to minsize if (i == nThis) { if (bHorz) m_szHorz.cx = m_szMinHorz.cx; else m_szVert.cy = m_szMinVert.cy; return TRUE; // the dockbar will split the row for us } // we have enough bars - go negotiate with them m_pDockBar->m_arrBars.InsertAt(i, (CControlBar*) NULL); nLast = i - 1; break; } if (bIsSizingBar) { nLengthActual += bHorz ? pBar->m_szHorz.cx - 2 : pBar->m_szVert.cy - 2; nWidthMax = max(nWidthMax, bHorz ? pBar->m_szHorz.cy : pBar->m_szVert.cx); } else nLengthAvail -= nLengthBar; } CSCBArray arrSCBars; GetRowSizingBars(arrSCBars); int nNumBars = arrSCBars.GetSize(); int nDelta = nLengthAvail - nLengthActual; // return faster when there is only one sizing bar per row (this one) if (nNumBars == 1) { ASSERT(arrSCBars[0] == this); if (nDelta == 0) return TRUE; m_bKeepSize = FALSE; (bHorz ? m_szHorz.cx : m_szVert.cy) += nDelta; return TRUE; } // make all the bars the same width for (i = 0; i < nNumBars; i++) if (bHorz) arrSCBars[i]->m_szHorz.cy = nWidthMax; else arrSCBars[i]->m_szVert.cx = nWidthMax; // distribute the difference between the bars, // but don't shrink them below their minsizes while (nDelta != 0) { int nDeltaOld = nDelta; for (i = 0; i < nNumBars; i++) { pBar = arrSCBars[i]; int nLMin = bHorz ? pBar->m_szMinHorz.cx : pBar->m_szMinVert.cy; int nL = bHorz ? pBar->m_szHorz.cx : pBar->m_szVert.cy; if ((nL == nLMin) && (nDelta < 0) || // already at min length pBar->m_bKeepSize) // or wants to keep its size continue; // sign of nDelta int nDelta2 = (nDelta == 0) ? 0 : ((nDelta < 0) ? -1 : 1); (bHorz ? pBar->m_szHorz.cx : pBar->m_szVert.cy) += nDelta2; nDelta -= nDelta2; if (nDelta == 0) break; } // clear m_bKeepSize flags if ((nDeltaOld == nDelta) || (nDelta == 0)) for (i = 0; i < nNumBars; i++) arrSCBars[i]->m_bKeepSize = FALSE; } return TRUE; } void CSizingControlBar::AlignControlBars() { int nFirst, nLast, nThis; GetRowInfo(nFirst, nLast, nThis); BOOL bHorz = IsHorzDocked(); BOOL bNeedRecalc = FALSE; int nAlign = bHorz ? -2 : 0; CRect rc, rcDock; m_pDockBar->GetWindowRect(&rcDock); for (int i = nFirst; i <= nLast; i++) { CSizingControlBar* pBar = (CSizingControlBar*) m_pDockBar->m_arrBars[i]; if (HIWORD(pBar) == 0) continue; // placeholder if (!pBar->IsVisible()) continue; pBar->GetWindowRect(&rc); rc.OffsetRect(-rcDock.TopLeft()); if (pBar->IsKindOf(RUNTIME_CLASS(CSizingControlBar))) rc = CRect(rc.TopLeft(), bHorz ? pBar->m_szHorz : pBar->m_szVert); if ((bHorz ? rc.left : rc.top) != nAlign) { if (!bHorz) rc.OffsetRect(0, nAlign - rc.top - 2); else if (m_nDockBarID == AFX_IDW_DOCKBAR_TOP) rc.OffsetRect(nAlign - rc.left, -2); else rc.OffsetRect(nAlign - rc.left, 0); pBar->MoveWindow(rc); bNeedRecalc = TRUE; } nAlign += (bHorz ? rc.Width() : rc.Height()) - 2; } if (bNeedRecalc) m_pDockSite->DelayRecalcLayout(); } void CSizingControlBar::OnUpdateCmdUI(CFrameWnd* pTarget, BOOL bDisableIfNoHndler) { UNUSED_ALWAYS(bDisableIfNoHndler); UNUSED_ALWAYS(pTarget); } void CSizingControlBar::LoadState(LPCTSTR lpszProfileName) { ASSERT_VALID(this); ASSERT(GetSafeHwnd()); // must be called after Create() #if defined(_SCB_REPLACE_MINIFRAME) && !defined(_SCB_MINIFRAME_CAPTION) // compensate the caption miscalculation in CFrameWnd::SetDockState() CDockState state; state.LoadState(lpszProfileName); UINT nID = GetDlgCtrlID(); for (int i = 0; i < state.m_arrBarInfo.GetSize(); i++) { CControlBarInfo* pInfo = (CControlBarInfo*)state.m_arrBarInfo[i]; ASSERT(pInfo != NULL); if (!pInfo->m_bFloating) continue; // this is a floating dockbar - check the ID array for (int j = 0; j < pInfo->m_arrBarID.GetSize(); j++) if ((DWORD) pInfo->m_arrBarID[j] == nID) { // found this bar - offset origin and save settings pInfo->m_pointPos.x++; pInfo->m_pointPos.y += ::GetSystemMetrics(SM_CYSMCAPTION) + 1; pInfo->SaveState(lpszProfileName, i); } } #endif //_SCB_REPLACE_MINIFRAME && !_SCB_MINIFRAME_CAPTION CWinApp* pApp = AfxGetApp(); TCHAR szSection[256]; wsprintf(szSection, _T("%s-SCBar-%d"), lpszProfileName, GetDlgCtrlID()); m_szHorz.cx = max(m_szMinHorz.cx, (int) pApp->GetProfileInt( szSection, _T("sizeHorzCX"), m_szHorz.cx)); m_szHorz.cy = max(m_szMinHorz.cy, (int) pApp->GetProfileInt( szSection, _T("sizeHorzCY"), m_szHorz.cy)); m_szVert.cx = max(m_szMinVert.cx, (int) pApp->GetProfileInt( szSection, _T("sizeVertCX"), m_szVert.cx)); m_szVert.cy = max(m_szMinVert.cy, (int) pApp->GetProfileInt( szSection, _T("sizeVertCY"), m_szVert.cy)); m_szFloat.cx = max(m_szMinFloat.cx, (int) pApp->GetProfileInt( szSection, _T("sizeFloatCX"), m_szFloat.cx)); m_szFloat.cy = max(m_szMinFloat.cy, (int) pApp->GetProfileInt( szSection, _T("sizeFloatCY"), m_szFloat.cy)); } void CSizingControlBar::SaveState(LPCTSTR lpszProfileName) { // place your SaveState or GlobalSaveState call in // CMainFrame's OnClose() or DestroyWindow(), not in OnDestroy() ASSERT_VALID(this); ASSERT(GetSafeHwnd()); CWinApp* pApp = AfxGetApp(); TCHAR szSection[256]; wsprintf(szSection, _T("%s-SCBar-%d"), lpszProfileName, GetDlgCtrlID()); pApp->WriteProfileInt(szSection, _T("sizeHorzCX"), m_szHorz.cx); pApp->WriteProfileInt(szSection, _T("sizeHorzCY"), m_szHorz.cy); pApp->WriteProfileInt(szSection, _T("sizeVertCX"), m_szVert.cx); pApp->WriteProfileInt(szSection, _T("sizeVertCY"), m_szVert.cy); pApp->WriteProfileInt(szSection, _T("sizeFloatCX"), m_szFloat.cx); pApp->WriteProfileInt(szSection, _T("sizeFloatCY"), m_szFloat.cy); } void CSizingControlBar::GlobalLoadState(CFrameWnd* pFrame, LPCTSTR lpszProfileName) { POSITION pos = pFrame->m_listControlBars.GetHeadPosition(); while (pos != NULL) { CSizingControlBar* pBar = (CSizingControlBar*) pFrame->m_listControlBars.GetNext(pos); ASSERT(pBar != NULL); if (pBar->IsKindOf(RUNTIME_CLASS(CSizingControlBar))) pBar->LoadState(lpszProfileName); } } void CSizingControlBar::GlobalSaveState(CFrameWnd* pFrame, LPCTSTR lpszProfileName) { POSITION pos = pFrame->m_listControlBars.GetHeadPosition(); while (pos != NULL) { CSizingControlBar* pBar = (CSizingControlBar*) pFrame->m_listControlBars.GetNext(pos); ASSERT(pBar != NULL); if (pBar->IsKindOf(RUNTIME_CLASS(CSizingControlBar))) pBar->SaveState(lpszProfileName); } } #ifdef _SCB_REPLACE_MINIFRAME #ifndef _SCB_MINIFRAME_CAPTION ///////////////////////////////////////////////////////////////////////////// // CSCBDockContext Drag Operations static void AdjustRectangle(CRect& rect, CPoint pt) { int nXOffset = (pt.x < rect.left) ? (pt.x - rect.left) : (pt.x > rect.right) ? (pt.x - rect.right) : 0; int nYOffset = (pt.y < rect.top) ? (pt.y - rect.top) : (pt.y > rect.bottom) ? (pt.y - rect.bottom) : 0; rect.OffsetRect(nXOffset, nYOffset); } void CSCBDockContext::StartDrag(CPoint pt) { ASSERT_VALID(m_pBar); m_bDragging = TRUE; InitLoop(); ASSERT((m_pBar->m_dwStyle & CBRS_SIZE_DYNAMIC) != 0); // get true bar size (including borders) CRect rect; m_pBar->GetWindowRect(rect); m_ptLast = pt; CSize sizeHorz = m_pBar->CalcDynamicLayout(0, LM_HORZ | LM_HORZDOCK); CSize sizeVert = m_pBar->CalcDynamicLayout(0, LM_VERTDOCK); CSize sizeFloat = m_pBar->CalcDynamicLayout(0, LM_HORZ | LM_MRUWIDTH); m_rectDragHorz = CRect(rect.TopLeft(), sizeHorz); m_rectDragVert = CRect(rect.TopLeft(), sizeVert); // calculate frame dragging rectangle m_rectFrameDragHorz = CRect(rect.TopLeft(), sizeFloat); #ifdef _MAC CMiniFrameWnd::CalcBorders(&m_rectFrameDragHorz, WS_THICKFRAME, WS_EX_FORCESIZEBOX); #else CMiniFrameWnd::CalcBorders(&m_rectFrameDragHorz, WS_THICKFRAME); #endif m_rectFrameDragHorz.DeflateRect(2, 2); m_rectFrameDragVert = m_rectFrameDragHorz; // adjust rectangles so that point is inside AdjustRectangle(m_rectDragHorz, pt); AdjustRectangle(m_rectDragVert, pt); AdjustRectangle(m_rectFrameDragHorz, pt); AdjustRectangle(m_rectFrameDragVert, pt); // initialize tracking state and enter tracking loop m_dwOverDockStyle = CanDock(); Move(pt); // call it here to handle special keys Track(); } #endif //_SCB_MINIFRAME_CAPTION ///////////////////////////////////////////////////////////////////////////// // CSCBMiniDockFrameWnd IMPLEMENT_DYNCREATE(CSCBMiniDockFrameWnd, baseCSCBMiniDockFrameWnd); BEGIN_MESSAGE_MAP(CSCBMiniDockFrameWnd, baseCSCBMiniDockFrameWnd) //{{AFX_MSG_MAP(CSCBMiniDockFrameWnd) ON_WM_NCLBUTTONDOWN() ON_WM_GETMINMAXINFO() ON_WM_WINDOWPOSCHANGING() ON_WM_SIZE() //}}AFX_MSG_MAP END_MESSAGE_MAP() BOOL CSCBMiniDockFrameWnd::Create(CWnd* pParent, DWORD dwBarStyle) { // set m_bInRecalcLayout to avoid flashing during creation // RecalcLayout will be called once something is docked m_bInRecalcLayout = TRUE; DWORD dwStyle = WS_POPUP|WS_CAPTION|WS_SYSMENU|MFS_MOVEFRAME| MFS_4THICKFRAME|MFS_SYNCACTIVE|MFS_BLOCKSYSMENU| FWS_SNAPTOBARS; if (dwBarStyle & CBRS_SIZE_DYNAMIC) dwStyle &= ~MFS_MOVEFRAME; DWORD dwExStyle = 0; #ifdef _MAC if (dwBarStyle & CBRS_SIZE_DYNAMIC) dwExStyle |= WS_EX_FORCESIZEBOX; else dwStyle &= ~(MFS_MOVEFRAME|MFS_4THICKFRAME); #endif if (!CMiniFrameWnd::CreateEx(dwExStyle, // NULL, &afxChNil, dwStyle, rectDefault, pParent)) NULL, NULL, dwStyle, rectDefault, pParent)) { m_bInRecalcLayout = FALSE; return FALSE; } dwStyle = dwBarStyle & (CBRS_ALIGN_LEFT|CBRS_ALIGN_RIGHT) ? CBRS_ALIGN_LEFT : CBRS_ALIGN_TOP; dwStyle |= dwBarStyle & CBRS_FLOAT_MULTI; CMenu* pSysMenu = GetSystemMenu(FALSE); //pSysMenu->DeleteMenu(SC_SIZE, MF_BYCOMMAND); CString strHide; if (strHide.LoadString(AFX_IDS_HIDE)) { pSysMenu->DeleteMenu(SC_CLOSE, MF_BYCOMMAND); pSysMenu->AppendMenu(MF_STRING|MF_ENABLED, SC_CLOSE, strHide); } // must initially create with parent frame as parent if (!m_wndDockBar.Create(pParent, WS_CHILD | WS_VISIBLE | dwStyle, AFX_IDW_DOCKBAR_FLOAT)) { m_bInRecalcLayout = FALSE; return FALSE; } // set parent to CMiniDockFrameWnd m_wndDockBar.SetParent(this); m_bInRecalcLayout = FALSE; return TRUE; } void CSCBMiniDockFrameWnd::OnNcLButtonDown(UINT nHitTest, CPoint point) { if (nHitTest == HTCAPTION || nHitTest == HTCLOSE) { baseCSCBMiniDockFrameWnd::OnNcLButtonDown(nHitTest, point); return; } if (GetSizingControlBar() != NULL) CMiniFrameWnd::OnNcLButtonDown(nHitTest, point); else baseCSCBMiniDockFrameWnd::OnNcLButtonDown(nHitTest, point); } CSizingControlBar* CSCBMiniDockFrameWnd::GetSizingControlBar() { CWnd* pWnd = GetWindow(GW_CHILD); // get the dockbar if (pWnd == NULL) return NULL; pWnd = pWnd->GetWindow(GW_CHILD); // get the controlbar if (pWnd == NULL) return NULL; if (!pWnd->IsKindOf(RUNTIME_CLASS(CSizingControlBar))) return NULL; return (CSizingControlBar*) pWnd; } void CSCBMiniDockFrameWnd::OnSize(UINT nType, int cx, int cy) { CSizingControlBar* pBar = GetSizingControlBar(); if ((pBar != NULL) && (GetStyle() & MFS_4THICKFRAME) == 0 && pBar->IsVisible() && cx + 4 >= pBar->m_szMinFloat.cx && cy + 4 >= pBar->m_szMinFloat.cy) pBar->m_szFloat = CSize(cx + 4, cy + 4); baseCSCBMiniDockFrameWnd::OnSize(nType, cx, cy); } void CSCBMiniDockFrameWnd::OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI) { baseCSCBMiniDockFrameWnd::OnGetMinMaxInfo(lpMMI); CSizingControlBar* pBar = GetSizingControlBar(); if (pBar != NULL) { CRect r(CPoint(0, 0), pBar->m_szMinFloat - CSize(4, 4)); #ifndef _SCB_MINIFRAME_CAPTION CMiniFrameWnd::CalcBorders(&r, WS_THICKFRAME); #else CMiniFrameWnd::CalcBorders(&r, WS_THICKFRAME|WS_CAPTION); #endif //_SCB_MINIFRAME_CAPTION lpMMI->ptMinTrackSize.x = r.Width(); lpMMI->ptMinTrackSize.y = r.Height(); } } void CSCBMiniDockFrameWnd::OnWindowPosChanging(WINDOWPOS FAR* lpwndpos) { if ((GetStyle() & MFS_4THICKFRAME) != 0) { CSizingControlBar* pBar = GetSizingControlBar(); if (pBar != NULL) { lpwndpos->flags |= SWP_NOSIZE; // don't size this time // prevents flicker pBar->m_pDockBar->ModifyStyle(0, WS_CLIPCHILDREN); // enable diagonal resizing DWORD dwStyleRemove = MFS_4THICKFRAME; #ifndef _SCB_MINIFRAME_CAPTION // remove caption dwStyleRemove |= WS_SYSMENU|WS_CAPTION; #endif ModifyStyle(dwStyleRemove, 0); DelayRecalcLayout(); pBar->PostMessage(WM_NCPAINT); } } CMiniFrameWnd::OnWindowPosChanging(lpwndpos); } #endif //_SCB_REPLACE_MINIFRAME
zzh-project-test
branches/ThumbViewer/src/sizecbar.cpp
C++
asf20
45,004
#ifndef _MEMDC_H_ #define _MEMDC_H_ ////////////////////////////////////////////////// // CMemDC - memory DC // // Author: Keith Rule // Email: keithr@europa.com // Copyright 1996-1999, Keith Rule // // You may freely use or modify this code provided this // Copyright is included in all derived versions. // // History - 10/3/97 Fixed scrolling bug. // Added print support. - KR // // 11/3/99 Fixed most common complaint. Added // background color fill. - KR // // 11/3/99 Added support for mapping modes other than // MM_TEXT as suggested by Lee Sang Hun. - KR // // This class implements a memory Device Context which allows // flicker free drawing. class CMemDC : public CDC { protected: CBitmap m_bitmap; // Offscreen bitmap CBitmap* m_oldBitmap; // bitmap originally found in CMemDC CDC* m_pDC; // Saves CDC passed in constructor CRect m_rect; // Rectangle of drawing area. BOOL m_bMemDC; // TRUE if CDC really is a Memory DC. void Construct(CDC* pDC) { ASSERT(pDC != NULL); // Some initialization m_pDC = pDC; m_oldBitmap = NULL; m_bMemDC = !pDC->IsPrinting(); if (m_bMemDC) { // Create a Memory DC CreateCompatibleDC(pDC); pDC->LPtoDP(&m_rect); m_bitmap.CreateCompatibleBitmap(pDC, m_rect.Width(), m_rect.Height()); m_oldBitmap = SelectObject(&m_bitmap); SetMapMode(pDC->GetMapMode()); pDC->DPtoLP(&m_rect); SetWindowOrg(m_rect.left, m_rect.top); } else { // Make a copy of the relevent parts of the current DC for printing m_bPrinting = pDC->m_bPrinting; m_hDC = pDC->m_hDC; m_hAttribDC = pDC->m_hAttribDC; } // Fill background FillSolidRect(m_rect, pDC->GetBkColor()); } // TRK begin public: CMemDC(CDC* pDC ) : CDC() { pDC->GetClipBox(&m_rect); Construct(pDC); } CMemDC(CDC* pDC, const RECT& rect) : CDC() { m_rect = rect ; Construct(pDC); } // TRK end virtual ~CMemDC() { if (m_bMemDC) { // Copy the offscreen bitmap onto the screen. m_pDC->BitBlt(m_rect.left, m_rect.top, m_rect.Width(), m_rect.Height(), this, m_rect.left, m_rect.top, SRCCOPY); //Swap back the original bitmap. SelectObject(m_oldBitmap); } else { // All we need to do is replace the DC with an illegal value, // this keeps us from accidently deleting the handles associated with // the CDC that was passed to the constructor. m_hDC = m_hAttribDC = NULL; } } // Allow usage as a pointer CMemDC* operator->() { return this; } // Allow usage as a pointer operator CMemDC*() { return this; } }; #endif
zzh-project-test
branches/ThumbViewer/src/memdc.h
C++
asf20
3,193
///////////////////////////////////////////////////////////////////////// // // CSizingControlBar Version 2.44 // // Created: Jan 24, 1998 Last Modified: March 31, 2002 // // See the official site at www.datamekanix.com for documentation and // the latest news. // ///////////////////////////////////////////////////////////////////////// // Copyright (C) 1998-2002 by Cristi Posea. All rights reserved. // // This code is free for personal and commercial use, providing this // notice remains intact in the source files and all eventual changes are // clearly marked with comments. // // You must obtain the author's consent before you can include this code // in a software library. // // No warrantee of any kind, express or implied, is included with this // software; use at your own risk, responsibility for damages (if any) to // anyone resulting from the use of this software rests entirely with the // user. // // Send bug reports, bug fixes, enhancements, requests, flames, etc. to // cristi@datamekanix.com or post them at the message board at the site. ///////////////////////////////////////////////////////////////////////// #if !defined(__SIZECBAR_H__) #define __SIZECBAR_H__ #include <afxpriv.h> // for CDockContext #include <afxtempl.h> // for CTypedPtrArray #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #if defined(_SCB_MINIFRAME_CAPTION) && !defined(_SCB_REPLACE_MINIFRAME) #error "_SCB_MINIFRAME_CAPTION requires _SCB_REPLACE_MINIFRAME" #endif ///////////////////////////////////////////////////////////////////////// // CSCBDockBar dummy class for access to protected members class CSCBDockBar : public CDockBar { friend class CSizingControlBar; }; ///////////////////////////////////////////////////////////////////////// // CSizingControlBar control bar styles #define SCBS_EDGELEFT 0x00000001 #define SCBS_EDGERIGHT 0x00000002 #define SCBS_EDGETOP 0x00000004 #define SCBS_EDGEBOTTOM 0x00000008 #define SCBS_EDGEALL 0x0000000F #define SCBS_SHOWEDGES 0x00000010 #define SCBS_SIZECHILD 0x00000020 ///////////////////////////////////////////////////////////////////////// // CSizingControlBar control bar #ifndef baseCSizingControlBar #define baseCSizingControlBar CControlBar #endif class CSizingControlBar; typedef CTypedPtrArray <CPtrArray, CSizingControlBar*> CSCBArray; class CSizingControlBar : public baseCSizingControlBar { DECLARE_DYNAMIC(CSizingControlBar); // Construction public: CSizingControlBar(); virtual BOOL Create(LPCTSTR lpszWindowName, CWnd* pParentWnd, CSize sizeDefault, BOOL bHasGripper, UINT nID, DWORD dwStyle = WS_CHILD | WS_VISIBLE | CBRS_TOP); virtual BOOL Create(LPCTSTR lpszWindowName, CWnd* pParentWnd, UINT nID, DWORD dwStyle = WS_CHILD | WS_VISIBLE | CBRS_TOP); // Attributes public: const BOOL IsFloating() const; const BOOL IsHorzDocked() const; const BOOL IsVertDocked() const; const BOOL IsSideTracking() const; const BOOL GetSCBStyle() const {return m_dwSCBStyle;} // Operations public: #if defined(_SCB_REPLACE_MINIFRAME) && !defined(_SCB_MINIFRAME_CAPTION) void EnableDocking(DWORD dwDockStyle); #endif virtual void LoadState(LPCTSTR lpszProfileName); virtual void SaveState(LPCTSTR lpszProfileName); static void GlobalLoadState(CFrameWnd* pFrame, LPCTSTR lpszProfileName); static void GlobalSaveState(CFrameWnd* pFrame, LPCTSTR lpszProfileName); void SetSCBStyle(DWORD dwSCBStyle) {m_dwSCBStyle = (dwSCBStyle & ~SCBS_EDGEALL);} // Overridables virtual void OnUpdateCmdUI(CFrameWnd* pTarget, BOOL bDisableIfNoHndler); // Overrides public: // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CSizingControlBar) public: virtual CSize CalcFixedLayout(BOOL bStretch, BOOL bHorz); virtual CSize CalcDynamicLayout(int nLength, DWORD dwMode); //}}AFX_VIRTUAL // Implementation public: virtual ~CSizingControlBar(); protected: // implementation helpers UINT GetEdgeHTCode(int nEdge); BOOL GetEdgeRect(CRect rcWnd, UINT nHitTest, CRect& rcEdge); virtual void StartTracking(UINT nHitTest, CPoint point); virtual void StopTracking(); virtual void OnTrackUpdateSize(CPoint& point); virtual void OnTrackInvertTracker(); virtual void NcPaintGripper(CDC* pDC, CRect rcClient); virtual void NcCalcClient(LPRECT pRc, UINT nDockBarID); virtual void AlignControlBars(); void GetRowInfo(int& nFirst, int& nLast, int& nThis); void GetRowSizingBars(CSCBArray& arrSCBars); void GetRowSizingBars(CSCBArray& arrSCBars, int& nThis); BOOL NegotiateSpace(int nLengthTotal, BOOL bHorz); protected: DWORD m_dwSCBStyle; UINT m_htEdge; CSize m_szHorz; CSize m_szVert; CSize m_szFloat; CSize m_szMinHorz; CSize m_szMinVert; CSize m_szMinFloat; int m_nTrackPosMin; int m_nTrackPosMax; int m_nTrackPosOld; int m_nTrackEdgeOfs; BOOL m_bTracking; BOOL m_bKeepSize; BOOL m_bParentSizing; BOOL m_bDragShowContent; UINT m_nDockBarID; int m_cxEdge; // Generated message map functions protected: //{{AFX_MSG(CSizingControlBar) afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnNcPaint(); afx_msg void OnNcCalcSize(BOOL bCalcValidRects, NCCALCSIZE_PARAMS FAR* lpncsp); //afx_msg UINT OnNcHitTest(CPoint point); afx_msg LRESULT OnNcHitTest(CPoint point); afx_msg void OnCaptureChanged(CWnd *pWnd); afx_msg void OnSettingChange(UINT uFlags, LPCTSTR lpszSection); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnNcLButtonDown(UINT nHitTest, CPoint point); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point); afx_msg void OnRButtonDown(UINT nFlags, CPoint point); afx_msg void OnWindowPosChanging(WINDOWPOS FAR* lpwndpos); afx_msg void OnPaint(); afx_msg void OnClose(); afx_msg void OnSize(UINT nType, int cx, int cy); //}}AFX_MSG afx_msg LRESULT OnSetText(WPARAM wParam, LPARAM lParam); DECLARE_MESSAGE_MAP() #ifdef _SCB_REPLACE_MINIFRAME friend class CSCBMiniDockFrameWnd; #endif //_SCB_REPLACE_MINIFRAME }; #ifdef _SCB_REPLACE_MINIFRAME #ifndef _SCB_MINIFRAME_CAPTION ///////////////////////////////////////////////////////////////////////// // CSCBDockContext dockcontext class CSCBDockContext : public CDockContext { public: // Construction CSCBDockContext(CControlBar* pBar) : CDockContext(pBar) {} // Drag Operations virtual void StartDrag(CPoint pt); }; #endif //_SCB_MINIFRAME_CAPTION ///////////////////////////////////////////////////////////////////////// // CSCBMiniDockFrameWnd miniframe #ifndef baseCSCBMiniDockFrameWnd #define baseCSCBMiniDockFrameWnd CMiniDockFrameWnd #endif class CSCBMiniDockFrameWnd : public baseCSCBMiniDockFrameWnd { DECLARE_DYNCREATE(CSCBMiniDockFrameWnd) // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CSCBMiniDockFrameWnd) public: virtual BOOL Create(CWnd* pParent, DWORD dwBarStyle); //}}AFX_VIRTUAL // Implementation public: CSizingControlBar* GetSizingControlBar(); //{{AFX_MSG(CSCBMiniDockFrameWnd) afx_msg void OnNcLButtonDown(UINT nHitTest, CPoint point); afx_msg void OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI); afx_msg void OnWindowPosChanging(WINDOWPOS FAR* lpwndpos); afx_msg void OnSize(UINT nType, int cx, int cy); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #endif //_SCB_REPLACE_MINIFRAME #endif // !defined(__SIZECBAR_H__)
zzh-project-test
branches/ThumbViewer/src/sizecbar.h
C++
asf20
8,008
#include "StdAfx.h" #include "CProTimer.h" CProTimer::CProTimer() { QueryPerformanceFrequency((LARGE_INTEGER *) &m_CounterFrequency); Reset(); } void CProTimer::Reset() { QueryPerformanceCounter((LARGE_INTEGER *) &m_ResetTime); } float CProTimer::GetTime(bool reset) { LONGLONG currentTime; QueryPerformanceCounter((LARGE_INTEGER *) &currentTime); LONGLONG diffTime = currentTime - m_ResetTime; if (reset) m_ResetTime = currentTime; return (float) (1000*diffTime) / (float) m_CounterFrequency; }
zzh-project-test
branches/ThumbViewer/src/CProTimer.cpp
C++
asf20
544
///////////////////////////////////////////////////////////////////////// // // CSizingControlBarG Version 2.44 // // Created: Jan 24, 1998 Last Modified: March 31, 2002 // // See the official site at www.datamekanix.com for documentation and // the latest news. // ///////////////////////////////////////////////////////////////////////// // Copyright (C) 1998-2002 by Cristi Posea. All rights reserved. // // This code is free for personal and commercial use, providing this // notice remains intact in the source files and all eventual changes are // clearly marked with comments. // // You must obtain the author's consent before you can include this code // in a software library. // // No warrantee of any kind, express or implied, is included with this // software; use at your own risk, responsibility for damages (if any) to // anyone resulting from the use of this software rests entirely with the // user. // // Send bug reports, bug fixes, enhancements, requests, flames, etc. to // cristi@datamekanix.com or post them at the message board at the site. ///////////////////////////////////////////////////////////////////////// #if !defined(__SCBARG_H__) #define __SCBARG_H__ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 ///////////////////////////////////////////////////////////////////////// // CSCBButton (button info) helper class class CSCBButton { public: CSCBButton(); void Move(CPoint ptTo) {ptOrg = ptTo; }; CRect GetRect() { return CRect(ptOrg, CSize(11, 11)); }; void Paint(CDC* pDC); BOOL bPushed; BOOL bRaised; protected: CPoint ptOrg; }; ///////////////////////////////////////////////////////////////////////// // CSizingControlBar control bar #ifndef baseCSizingControlBarG #define baseCSizingControlBarG CSizingControlBar #endif class CSizingControlBarG : public baseCSizingControlBarG { DECLARE_DYNAMIC(CSizingControlBarG); // Construction public: CSizingControlBarG(); // Attributes public: virtual BOOL HasGripper() const; // Operations public: // Overridables virtual void OnUpdateCmdUI(CFrameWnd* pTarget, BOOL bDisableIfNoHndler); // Overrides public: // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CSizingControlBarG) //}}AFX_VIRTUAL // Implementation public: virtual ~CSizingControlBarG(); protected: // implementation helpers virtual void NcPaintGripper(CDC* pDC, CRect rcClient); virtual void NcCalcClient(LPRECT pRc, UINT nDockBarID); protected: int m_cyGripper; CSCBButton m_biHide; // Generated message map functions protected: //{{AFX_MSG(CSizingControlBarG) //afx_msg UINT OnNcHitTest(CPoint point); afx_msg LRESULT OnNcHitTest(CPoint point); afx_msg void OnNcLButtonUp(UINT nHitTest, CPoint point); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #endif // !defined(__SCBARG_H__)
zzh-project-test
branches/ThumbViewer/src/scbarg.h
C++
asf20
3,020
// ThumbViewer.h : main header file for the THUMBVIEWER application // #if !defined(AFX_THUMBVIEWER_H__71E2C240_CCFB_4DFD_836E_EECD986C32A8__INCLUDED_) #define AFX_THUMBVIEWER_H__71E2C240_CCFB_4DFD_836E_EECD986C32A8__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif #include "resource.h" // main symbols ///////////////////////////////////////////////////////////////////////////// // CThumbViewerApp: // See ThumbViewer.cpp for the implementation of this class // class CThumbViewerApp : public CWinApp { public: CThumbViewerApp(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CThumbViewerApp) public: virtual BOOL InitInstance(); //}}AFX_VIRTUAL // Implementation //{{AFX_MSG(CThumbViewerApp) afx_msg void OnAppAbout(); // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_THUMBVIEWER_H__71E2C240_CCFB_4DFD_836E_EECD986C32A8__INCLUDED_)
zzh-project-test
branches/ThumbViewer/src/ThumbViewer.h
C++
asf20
1,409
#if !defined(AFX_DLGCTRLLISTEX_H__FEA58268_E891_4452_A845_648A4EC86910__INCLUDED_) #define AFX_DLGCTRLLISTEX_H__FEA58268_E891_4452_A845_648A4EC86910__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // DlgCtrlListEx.h : header file // ///////////////////////////////////////////////////////////////////////////// // DlgCtrlListEx dialog #include "ListCtrlEx.h" class DlgCtrlListEx : public CDialog { // Construction public: DlgCtrlListEx(CWnd* pParent = NULL); // standard constructor CListCtrlEx m_list; // Dialog Data //{{AFX_DATA(DlgCtrlListEx) enum { IDD = IDD_DLG_CTRL }; // NOTE: the ClassWizard will add data members here //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(DlgCtrlListEx) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(DlgCtrlListEx) // NOTE: the ClassWizard will add member functions here //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_DLGCTRLLISTEX_H__FEA58268_E891_4452_A845_648A4EC86910__INCLUDED_)
zzh-project-test
branches/ThumbViewer/src/DlgCtrlListEx.h
C++
asf20
1,333
#if !defined(AFX_DLGLISTCTRL_H__B5499AD9_3B77_4B3B_AC8C_CBDA0051C32B__INCLUDED_) #define AFX_DLGLISTCTRL_H__B5499AD9_3B77_4B3B_AC8C_CBDA0051C32B__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // DlgListCtrl.h : header file // ///////////////////////////////////////////////////////////////////////////// // DlgListCtrl dialog //#include "ListCtrlEx.h" class DlgListCtrl : public CDialog { // Construction public: DlgListCtrl(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(DlgListCtrl) enum { IDD = IDD_DLG_LISTCTRL }; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(DlgListCtrl) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(DlgListCtrl) // NOTE: the ClassWizard will add member functions here //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_DLGLISTCTRL_H__B5499AD9_3B77_4B3B_AC8C_CBDA0051C32B__INCLUDED_)
zzh-project-test
branches/ThumbViewer/src/DlgListCtrl.h
C++
asf20
1,240
// DirectoryTreeBar.cpp : implementation file // #include "stdafx.h" #include "ThumbViewer.h" #include "DirectoryTreeBar.h" #include "MainFrm.h" #include "ThumbViewerDoc.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CDirectoryTreeBar CDirectoryTreeBar::CDirectoryTreeBar() { } CDirectoryTreeBar::~CDirectoryTreeBar() { } BEGIN_MESSAGE_MAP(CDirectoryTreeBar, CSizingControlBarG) //{{AFX_MSG_MAP(CDirectoryTreeBar) ON_WM_CREATE() ON_WM_SIZE() ON_WM_NCLBUTTONUP() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDirectoryTreeBar message handlers int CDirectoryTreeBar::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CSizingControlBarG::OnCreate(lpCreateStruct) == -1) return -1; // TODO: Add your specialized creation code here CRect rect; GetClientRect( &rect ); m_TreeCtrl.Create(WS_VISIBLE|WS_CHILD|TVS_HASLINES|TVS_HASBUTTONS|TVS_LINESATROOT, rect, this, IDC_TREEDIR); m_TreeCtrl.Initialize(); return 0; } void CDirectoryTreeBar::OnSize(UINT nType, int cx, int cy) { CSizingControlBarG::OnSize(nType, cx, cy); // TODO: Add your message handler code here CRect rc; GetClientRect(rc); m_TreeCtrl.MoveWindow(rc); } // Not closing window, just hiding void CDirectoryTreeBar::OnNcLButtonUp(UINT nHitTest, CPoint point) { // TODO: Add your message handler code here and/or call default if( OnNcHitTest(point) == HTCLOSE ) { CMainFrame* pFrame=(CMainFrame*)AfxGetMainWnd(); pFrame->SendMessage(WM_COMMAND, ID_VIEW_DIRECTORY_BAR); } CSizingControlBarG::OnNcLButtonUp(nHitTest, point); }
zzh-project-test
branches/ThumbViewer/src/DirectoryTreeBar.cpp
C++
asf20
1,811
#if !defined(AFX_PREVIEWBAR_H__426DCEB6_0A8E_4609_B433_2675C303E9DA__INCLUDED_) #define AFX_PREVIEWBAR_H__426DCEB6_0A8E_4609_B433_2675C303E9DA__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // PreviewBar.h : header file // ///////////////////////////////////////////////////////////////////////////// // CPreviewBar window class CPreviewBar : public CSizingControlBarCF { // Construction public: CPreviewBar(); // Attributes public: CStatic m_wndCanvas; // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CPreviewBar) //}}AFX_VIRTUAL // Implementation public: virtual ~CPreviewBar(); // Generated message map functions protected: //{{AFX_MSG(CPreviewBar) afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg LRESULT UpdataPreView( WPARAM wParam, LPARAM lParam ); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_PREVIEWBAR_H__426DCEB6_0A8E_4609_B433_2675C303E9DA__INCLUDED_)
zzh-project-test
branches/ThumbViewer/src/PreviewBar.h
C++
asf20
1,426
///////////////////////////////////////////////////////////////////////// // // CSizingControlBarG Version 2.44 // // Created: Jan 24, 1998 Last Modified: March 31, 2002 // // See the official site at www.datamekanix.com for documentation and // the latest news. // ///////////////////////////////////////////////////////////////////////// // Copyright (C) 1998-2002 by Cristi Posea. All rights reserved. // // This code is free for personal and commercial use, providing this // notice remains intact in the source files and all eventual changes are // clearly marked with comments. // // You must obtain the author's consent before you can include this code // in a software library. // // No warrantee of any kind, express or implied, is included with this // software; use at your own risk, responsibility for damages (if any) to // anyone resulting from the use of this software rests entirely with the // user. // // Send bug reports, bug fixes, enhancements, requests, flames, etc. to // cristi@datamekanix.com or post them at the message board at the site. ///////////////////////////////////////////////////////////////////////// // sizecbar.cpp : implementation file // #include "stdafx.h" //#include "..\StdAfx.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////// // CSizingControlBarG IMPLEMENT_DYNAMIC(CSizingControlBarG, baseCSizingControlBarG); CSizingControlBarG::CSizingControlBarG() { m_cyGripper = 12; } CSizingControlBarG::~CSizingControlBarG() { } BEGIN_MESSAGE_MAP(CSizingControlBarG, baseCSizingControlBarG) //{{AFX_MSG_MAP(CSizingControlBarG) ON_WM_NCLBUTTONUP() ON_WM_NCHITTEST() //}}AFX_MSG_MAP ON_MESSAGE(WM_SETTEXT, OnSetText) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////// // CSizingControlBarG message handlers ///////////////////////////////////////////////////////////////////////// // Mouse Handling // void CSizingControlBarG::OnNcLButtonUp(UINT nHitTest, CPoint point) { if (nHitTest == HTCLOSE) m_pDockSite->ShowControlBar(this, FALSE, FALSE); // hide baseCSizingControlBarG::OnNcLButtonUp(nHitTest, point); } void CSizingControlBarG::NcCalcClient(LPRECT pRc, UINT nDockBarID) { CRect rcBar(pRc); // save the bar rect // subtract edges baseCSizingControlBarG::NcCalcClient(pRc, nDockBarID); if (!HasGripper()) return; CRect rc(pRc); // the client rect as calculated by the base class BOOL bHorz = (nDockBarID == AFX_IDW_DOCKBAR_TOP) || (nDockBarID == AFX_IDW_DOCKBAR_BOTTOM); if (bHorz) rc.DeflateRect(m_cyGripper, 0, 0, 0); else rc.DeflateRect(0, m_cyGripper, 0, 0); // set position for the "x" (hide bar) button CPoint ptOrgBtn; if (bHorz) ptOrgBtn = CPoint(rc.left - 13, rc.top); else ptOrgBtn = CPoint(rc.right - 12, rc.top - 13); m_biHide.Move(ptOrgBtn - rcBar.TopLeft()); *pRc = rc; } void CSizingControlBarG::NcPaintGripper(CDC* pDC, CRect rcClient) { if (!HasGripper()) return; // paints a simple "two raised lines" gripper // override this if you want a more sophisticated gripper CRect gripper = rcClient; CRect rcbtn = m_biHide.GetRect(); BOOL bHorz = IsHorzDocked(); gripper.DeflateRect(1, 1); if (bHorz) { // gripper at left gripper.left -= m_cyGripper; gripper.right = gripper.left + 3; gripper.top = rcbtn.bottom + 3; } else { // gripper at top gripper.top -= m_cyGripper; gripper.bottom = gripper.top + 3; gripper.right = rcbtn.left - 3; } pDC->Draw3dRect(gripper, ::GetSysColor(COLOR_BTNHIGHLIGHT), ::GetSysColor(COLOR_BTNSHADOW)); gripper.OffsetRect(bHorz ? 3 : 0, bHorz ? 0 : 3); pDC->Draw3dRect(gripper, ::GetSysColor(COLOR_BTNHIGHLIGHT), ::GetSysColor(COLOR_BTNSHADOW)); m_biHide.Paint(pDC); } //UINT CSizingControlBarG::OnNcHitTest(CPoint point) LRESULT CSizingControlBarG::OnNcHitTest(CPoint point) { CRect rcBar; GetWindowRect(rcBar); UINT nRet = baseCSizingControlBarG::OnNcHitTest(point); if (nRet != HTCLIENT) return nRet; CRect rc = m_biHide.GetRect(); rc.OffsetRect(rcBar.TopLeft()); if (rc.PtInRect(point)) return HTCLOSE; return HTCLIENT; } ///////////////////////////////////////////////////////////////////////// // CSizingControlBarG implementation helpers void CSizingControlBarG::OnUpdateCmdUI(CFrameWnd* pTarget, BOOL bDisableIfNoHndler) { UNUSED_ALWAYS(bDisableIfNoHndler); UNUSED_ALWAYS(pTarget); if (!HasGripper()) return; BOOL bNeedPaint = FALSE; CPoint pt; ::GetCursorPos(&pt); BOOL bHit = (OnNcHitTest(pt) == HTCLOSE); BOOL bLButtonDown = (::GetKeyState(VK_LBUTTON) < 0); BOOL bWasPushed = m_biHide.bPushed; m_biHide.bPushed = bHit && bLButtonDown; BOOL bWasRaised = m_biHide.bRaised; m_biHide.bRaised = bHit && !bLButtonDown; bNeedPaint |= (m_biHide.bPushed ^ bWasPushed) || (m_biHide.bRaised ^ bWasRaised); if (bNeedPaint) SendMessage(WM_NCPAINT); } ///////////////////////////////////////////////////////////////////////// // CSCBButton CSCBButton::CSCBButton() { bRaised = FALSE; bPushed = FALSE; } void CSCBButton::Paint(CDC* pDC) { CRect rc = GetRect(); if (bPushed) pDC->Draw3dRect(rc, ::GetSysColor(COLOR_BTNSHADOW), ::GetSysColor(COLOR_BTNHIGHLIGHT)); else if (bRaised) pDC->Draw3dRect(rc, ::GetSysColor(COLOR_BTNHIGHLIGHT), ::GetSysColor(COLOR_BTNSHADOW)); COLORREF clrOldTextColor = pDC->GetTextColor(); pDC->SetTextColor(::GetSysColor(COLOR_BTNTEXT)); int nPrevBkMode = pDC->SetBkMode(TRANSPARENT); CFont font; int ppi = pDC->GetDeviceCaps(LOGPIXELSX); int pointsize = MulDiv(60, 96, ppi); // 6 points at 96 ppi font.CreatePointFont(pointsize, _T("Marlett")); CFont* oldfont = pDC->SelectObject(&font); pDC->TextOut(ptOrg.x + 2, ptOrg.y + 2, CString(_T("r"))); // x-like pDC->SelectObject(oldfont); pDC->SetBkMode(nPrevBkMode); pDC->SetTextColor(clrOldTextColor); } BOOL CSizingControlBarG::HasGripper() const { #if defined(_SCB_MINIFRAME_CAPTION) || !defined(_SCB_REPLACE_MINIFRAME) // if the miniframe has a caption, don't display the gripper if (IsFloating()) return FALSE; #endif //_SCB_MINIFRAME_CAPTION return TRUE; }
zzh-project-test
branches/ThumbViewer/src/scbarg.cpp
C++
asf20
6,906
//{{NO_DEPENDENCIES}} // Microsoft Developer Studio generated include file. // Used by ThumbViewer.rc // #define IDD_ABOUTBOX 100 #define IDC_IMAGEPREVIEW 101 #define IDC_TREEDIR 102 #define IDR_MAINFRAME 128 #define IDR_THUMBVTYPE 129 #define IDC_LIST1 1000 #define ID_VIEW_DIRECTORY_BAR 32771 #define ID_VIEW_PREVIEW_BAR 32772 #define ID_STOP_THREAD 32773 #define ID_TEST 32774 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_3D_CONTROLS 1 #define _APS_NEXT_RESOURCE_VALUE 133 #define _APS_NEXT_COMMAND_VALUE 32775 #define _APS_NEXT_CONTROL_VALUE 1001 #define _APS_NEXT_SYMED_VALUE 103 #endif #endif
zzh-project-test
branches/ThumbViewer/src/resource.h
C
asf20
922
///////////////////////////////////////////////////////////////////////// // // CSizingControlBarCF Version 2.44 // // Created: Dec 21, 1998 Last Modified: March 31, 2002 // // See the official site at www.datamekanix.com for documentation and // the latest news. // ///////////////////////////////////////////////////////////////////////// // Copyright (C) 1998-2002 by Cristi Posea. All rights reserved. // // This code is free for personal and commercial use, providing this // notice remains intact in the source files and all eventual changes are // clearly marked with comments. // // You must obtain the author's consent before you can include this code // in a software library. // // No warrantee of any kind, express or implied, is included with this // software; use at your own risk, responsibility for damages (if any) to // anyone resulting from the use of this software rests entirely with the // user. // // Send bug reports, bug fixes, enhancements, requests, flames, etc. to // cristi@datamekanix.com or post them at the message board at the site. ///////////////////////////////////////////////////////////////////////// #include <stdafx.h> #include "scbarcf.h" ///////////////////////////////////////////////////////////////////////// // CSizingControlBarCF IMPLEMENT_DYNAMIC(CSizingControlBarCF, baseCSizingControlBarCF); int CALLBACK EnumFontFamProc(ENUMLOGFONT FAR *lpelf, NEWTEXTMETRIC FAR *lpntm, int FontType, LPARAM lParam) { UNUSED_ALWAYS(lpelf); UNUSED_ALWAYS(lpntm); UNUSED_ALWAYS(FontType); UNUSED_ALWAYS(lParam); return 0; } CSizingControlBarCF::CSizingControlBarCF() { m_bActive = FALSE; CDC dc; dc.CreateCompatibleDC(NULL); m_sFontFace = (::EnumFontFamilies(dc.m_hDC, _T("Tahoma"), (FONTENUMPROC) EnumFontFamProc, 0) == 0) ? _T("Tahoma") : _T("Arial"); dc.DeleteDC(); } BEGIN_MESSAGE_MAP(CSizingControlBarCF, baseCSizingControlBarCF) //{{AFX_MSG_MAP(CSizingControlBarCF) //}}AFX_MSG_MAP ON_MESSAGE(WM_SETTEXT, OnSetText) END_MESSAGE_MAP() void CSizingControlBarCF::OnUpdateCmdUI(CFrameWnd* pTarget, BOOL bDisableIfNoHndler) { baseCSizingControlBarCF::OnUpdateCmdUI(pTarget, bDisableIfNoHndler); if (!HasGripper()) return; BOOL bNeedPaint = FALSE; CWnd* pFocus = GetFocus(); BOOL bActiveOld = m_bActive; m_bActive = (pFocus->GetSafeHwnd() && IsChild(pFocus)); if (m_bActive != bActiveOld) bNeedPaint = TRUE; if (bNeedPaint) SendMessage(WM_NCPAINT); } // gradient defines (if not already defined) #ifndef COLOR_GRADIENTACTIVECAPTION #define COLOR_GRADIENTACTIVECAPTION 27 #define COLOR_GRADIENTINACTIVECAPTION 28 #define SPI_GETGRADIENTCAPTIONS 0x1008 #endif void CSizingControlBarCF::NcPaintGripper(CDC* pDC, CRect rcClient) { if (!HasGripper()) return; // compute the caption rectangle BOOL bHorz = IsHorzDocked(); CRect rcGrip = rcClient; CRect rcBtn = m_biHide.GetRect(); if (bHorz) { // right side gripper rcGrip.left -= m_cyGripper + 1; rcGrip.right = rcGrip.left + 11; rcGrip.top = rcBtn.bottom + 3; } else { // gripper at top rcGrip.top -= m_cyGripper + 1; rcGrip.bottom = rcGrip.top + 11; rcGrip.right = rcBtn.left - 3; } rcGrip.InflateRect(bHorz ? 1 : 0, bHorz ? 0 : 1); // draw the caption background //CBrush br; COLORREF clrCptn = m_bActive ? ::GetSysColor(COLOR_ACTIVECAPTION) : ::GetSysColor(COLOR_INACTIVECAPTION); // query gradient info (usually TRUE for Win98/Win2k) BOOL bGradient = FALSE; ::SystemParametersInfo(SPI_GETGRADIENTCAPTIONS, 0, &bGradient, 0); if (!bGradient) pDC->FillSolidRect(&rcGrip, clrCptn); // solid color else { // gradient from left to right or from bottom to top // get second gradient color (the right end) COLORREF clrCptnRight = m_bActive ? ::GetSysColor(COLOR_GRADIENTACTIVECAPTION) : ::GetSysColor(COLOR_GRADIENTINACTIVECAPTION); // this will make 2^6 = 64 fountain steps int nShift = 6; int nSteps = 1 << nShift; for (int i = 0; i < nSteps; i++) { // do a little alpha blending int nR = (GetRValue(clrCptn) * (nSteps - i) + GetRValue(clrCptnRight) * i) >> nShift; int nG = (GetGValue(clrCptn) * (nSteps - i) + GetGValue(clrCptnRight) * i) >> nShift; int nB = (GetBValue(clrCptn) * (nSteps - i) + GetBValue(clrCptnRight) * i) >> nShift; COLORREF cr = RGB(nR, nG, nB); // then paint with the resulting color CRect r2 = rcGrip; if (bHorz) { r2.bottom = rcGrip.bottom - ((i * rcGrip.Height()) >> nShift); r2.top = rcGrip.bottom - (((i + 1) * rcGrip.Height()) >> nShift); if (r2.Height() > 0) pDC->FillSolidRect(r2, cr); } else { r2.left = rcGrip.left + ((i * rcGrip.Width()) >> nShift); r2.right = rcGrip.left + (((i + 1) * rcGrip.Width()) >> nShift); if (r2.Width() > 0) pDC->FillSolidRect(r2, cr); } } } // draw the caption text - first select a font CFont font; int ppi = pDC->GetDeviceCaps(LOGPIXELSX); int pointsize = MulDiv(85, 96, ppi); // 8.5 points at 96 ppi LOGFONT lf; BOOL bFont = font.CreatePointFont(pointsize, m_sFontFace); if (bFont) { // get the text color COLORREF clrCptnText = m_bActive ? ::GetSysColor(COLOR_CAPTIONTEXT) : ::GetSysColor(COLOR_INACTIVECAPTIONTEXT); int nOldBkMode = pDC->SetBkMode(TRANSPARENT); COLORREF clrOldText = pDC->SetTextColor(clrCptnText); if (bHorz) { // rotate text 90 degrees CCW if horizontally docked font.GetLogFont(&lf); font.DeleteObject(); lf.lfEscapement = 900; font.CreateFontIndirect(&lf); } CFont* pOldFont = pDC->SelectObject(&font); CString sTitle; GetWindowText(sTitle); CPoint ptOrg = bHorz ? CPoint(rcGrip.left - 1, rcGrip.bottom - 3) : CPoint(rcGrip.left + 3, rcGrip.top - 1); pDC->ExtTextOut(ptOrg.x, ptOrg.y, ETO_CLIPPED, rcGrip, sTitle, NULL); pDC->SelectObject(pOldFont); pDC->SetBkMode(nOldBkMode); pDC->SetTextColor(clrOldText); } // draw the button m_biHide.Paint(pDC); } LRESULT CSizingControlBarCF::OnSetText(WPARAM wParam, LPARAM lParam) { LRESULT lResult = baseCSizingControlBarCF::OnSetText(wParam, lParam); SendMessage(WM_NCPAINT); return lResult; }
zzh-project-test
branches/ThumbViewer/src/scbarcf.cpp
C++
asf20
7,344
#if !defined(AFX_DIRTREECTRL_H__A6FFC441_2808_4303_BDFA_6DDD96AC96D5__INCLUDED_) #define AFX_DIRTREECTRL_H__A6FFC441_2808_4303_BDFA_6DDD96AC96D5__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // DirTreeCtrl.h : header file // #include <Shlobj.h> #include <direct.h> ///////////////////////////////////////////////////////////////////////////// // CDirTreeCtrl window class CDirTreeCtrl : public CTreeCtrl { // Construction public: CDirTreeCtrl(); // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CDirTreeCtrl) public: virtual BOOL PreTranslateMessage(MSG* pMsg); //}}AFX_VIRTUAL // Implementation public: HTREEITEM AddNewDirectory(); CString GetSelectedDirectory(); // CString GetFullPath (HTREEITEM item); void RefreshSubItems(HTREEITEM hParent); void RefreshShellRoot(LPCITEMIDLIST pidlRoot, BOOL bIncludeFiles = FALSE); void Initialize(); virtual ~CDirTreeCtrl(); // Generated message map functions protected: //{{AFX_MSG(CDirTreeCtrl) afx_msg void OnItemexpanding(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnEndlabeledit(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnSelchanged(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnBeginlabeledit(NMHDR* pNMHDR, LRESULT* pResult); //}}AFX_MSG DECLARE_MESSAGE_MAP() private: BOOL m_currentEditItemChildren; CString m_SelectedDirectory; HTREEITEM m_desktop_root; BOOL m_bIncludeFiles; LPITEMIDLIST m_pidlRoot; IMalloc* m_pMalloc; IShellFolder* m_pDesktopFolder; // manage PIDLs static int ILGetLength(LPCITEMIDLIST pidl); static LPCITEMIDLIST ILGetNext(LPCITEMIDLIST pidl); static LPCITEMIDLIST ILGetLast(LPCITEMIDLIST pidl); LPITEMIDLIST ILCombine(LPCITEMIDLIST pidl1, LPCITEMIDLIST pidl2); LPITEMIDLIST ILCloneFirst(LPCITEMIDLIST pidl); LPITEMIDLIST ILClone(LPCITEMIDLIST pidl) { return ILCombine(pidl, NULL); }; void PreExpandItem(HTREEITEM hItem); // before expanding void ExpandItem(HTREEITEM hItem); // after expanded BOOL NeedsChildren(HTREEITEM hParent); // true if no child items void DeleteChildren(HTREEITEM hParent); void PopulateRoot(); BOOL WantsRefresh(HTREEITEM hItem); BOOL PopulateItem(HTREEITEM hParent); // CString GetPathFromHere (CString s, HTREEITEM itm); BOOL CDirTreeCtrl::FillItem(TVITEM& item, LPCITEMIDLIST pidl, IShellFolder* pParentFolder, LPCITEMIDLIST pidlRel); static int CALLBACK CompareFunc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort); HTREEITEM m_hItemToPopulate; // item being populated }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_DIRTREECTRL_H__A6FFC441_2808_4303_BDFA_6DDD96AC96D5__INCLUDED_)
zzh-project-test
branches/ThumbViewer/src/DirTreeCtrl.h
C++
asf20
2,946
// stdafx.cpp : source file that includes just the standard includes // ThumbViewer.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
zzh-project-test
branches/ThumbViewer/src/StdAfx.cpp
C++
asf20
213
// DlgCtrlListEx.cpp : implementation file // #include "stdafx.h" #include "thumbviewer.h" #include "DlgCtrlListEx.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // DlgCtrlListEx dialog DlgCtrlListEx::DlgCtrlListEx(CWnd* pParent /*=NULL*/) : CDialog(DlgCtrlListEx::IDD, pParent) { //{{AFX_DATA_INIT(DlgCtrlListEx) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } void DlgCtrlListEx::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(DlgCtrlListEx) // NOTE: the ClassWizard will add DDX and DDV calls here DDX_Control(pDX, IDC_LIST_CTRLEX, m_list); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(DlgCtrlListEx, CDialog) //{{AFX_MSG_MAP(DlgCtrlListEx) // NOTE: the ClassWizard will add message map macros here //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // DlgCtrlListEx message handlers
zzh-project-test
branches/ThumbViewer/src/DlgCtrlListEx.cpp
C++
asf20
1,109
/* * File: xfile.h * Purpose: General Purpose File Class */ /* -------------------------------------------------------------------------------- COPYRIGHT NOTICE, DISCLAIMER, and LICENSE: CxFile (c) 11/May/2002 Davide Pizzolato - www.xdp.it CxFile version 2.00 23/Aug/2002 Special thanks to Chris Shearer Cooper for new features, enhancements and bugfixes Covered code is provided under this license on an "as is" basis, without warranty of any kind, either expressed or implied, including, without limitation, warranties that the covered code is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire risk as to the quality and performance of the covered code is with you. Should any covered code prove defective in any respect, you (not the initial developer or any other contributor) assume the cost of any necessary servicing, repair or correction. This disclaimer of warranty constitutes an essential part of this license. No use of any covered code is authorized hereunder except under this disclaimer. Permission is hereby granted to use, copy, modify, and distribute this source code, or portions hereof, for any purpose, including commercial applications, freely and without fee, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. -------------------------------------------------------------------------------- */ #if !defined(__xfile_h) #define __xfile_h #ifdef WIN32 #include <windows.h> #endif #include <stdio.h> #include <stdlib.h> #include "ximadef.h" class DLL_EXP CxFile { public: CxFile(void) { }; virtual ~CxFile() { }; virtual bool Close() = 0; virtual size_t Read(void *buffer, size_t size, size_t count) = 0; virtual size_t Write(const void *buffer, size_t size, size_t count) = 0; virtual bool Seek(long offset, int origin) = 0; virtual long Tell() = 0; virtual long Size() = 0; virtual bool Flush() = 0; virtual bool Eof() = 0; virtual long Error() = 0; virtual bool PutC(unsigned char c) { // Default implementation size_t nWrote = Write(&c, 1, 1); return (bool)(nWrote == 1); } virtual long GetC() = 0; }; #endif //__xfile_h
zzh-project-test
branches/ThumbViewer/include/xfile.h
C++
asf20
2,663
#if !defined(__xmemfile_h) #define __xmemfile_h #include "xfile.h" ////////////////////////////////////////////////////////// class DLL_EXP CxMemFile : public CxFile { public: CxMemFile(BYTE* pBuffer = NULL, DWORD size = 0); ~CxMemFile(); bool Open(); BYTE* GetBuffer(bool bDetachBuffer = true); virtual bool Close(); virtual size_t Read(void *buffer, size_t size, size_t count); virtual size_t Write(const void *buffer, size_t size, size_t count); virtual bool Seek(long offset, int origin); virtual long Tell(); virtual long Size(); virtual bool Flush(); virtual bool Eof(); virtual long Error(); virtual bool PutC(unsigned char c); virtual long GetC(); protected: void Alloc(DWORD nBytes); void Free(); BYTE* m_pBuffer; DWORD m_Size; bool m_bFreeOnClose; long m_Position; //current position long m_Edge; //buffer size }; #endif
zzh-project-test
branches/ThumbViewer/include/xmemfile.h
C++
asf20
900
/* * File: ximage.h * Purpose: General Purpose Image Class */ /* -------------------------------------------------------------------------------- COPYRIGHT NOTICE, DISCLAIMER, and LICENSE: CxImage version 5.99c 17/Oct/2004 CxImage : Copyright (C) 2001 - 2004, Davide Pizzolato Original CImage and CImageIterator implementation are: Copyright (C) 1995, Alejandro Aguilar Sierra (asierra(at)servidor(dot)unam(dot)mx) Covered code is provided under this license on an "as is" basis, without warranty of any kind, either expressed or implied, including, without limitation, warranties that the covered code is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire risk as to the quality and performance of the covered code is with you. Should any covered code prove defective in any respect, you (not the initial developer or any other contributor) assume the cost of any necessary servicing, repair or correction. This disclaimer of warranty constitutes an essential part of this license. No use of any covered code is authorized hereunder except under this disclaimer. Permission is hereby granted to use, copy, modify, and distribute this source code, or portions hereof, for any purpose, including commercial applications, freely and without fee, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. -------------------------------------------------------------------------------- Other information: about CxImage, and the latest version, can be found at the CxImage home page: http://www.xdp.it -------------------------------------------------------------------------------- */ #if !defined(__CXIMAGE_H) #define __CXIMAGE_H #if _MSC_VER > 1000 #pragma once #endif ///////////////////////////////////////////////////////////////////////////// #include "xfile.h" #include "xiofile.h" #include "xmemfile.h" #include "ximadef.h" //<vho> adjust some #define /* see "ximacfg.h" for CxImage configuration options */ ///////////////////////////////////////////////////////////////////////////// // CxImage formats enumerator enum ENUM_CXIMAGE_FORMATS{ CXIMAGE_FORMAT_UNKNOWN, #if CXIMAGE_SUPPORT_BMP CXIMAGE_FORMAT_BMP, #endif #if CXIMAGE_SUPPORT_GIF CXIMAGE_FORMAT_GIF, #endif #if CXIMAGE_SUPPORT_JPG CXIMAGE_FORMAT_JPG, #endif #if CXIMAGE_SUPPORT_PNG CXIMAGE_FORMAT_PNG, #endif #if CXIMAGE_SUPPORT_MNG CXIMAGE_FORMAT_MNG, #endif #if CXIMAGE_SUPPORT_ICO CXIMAGE_FORMAT_ICO, #endif #if CXIMAGE_SUPPORT_TIF CXIMAGE_FORMAT_TIF, #endif #if CXIMAGE_SUPPORT_TGA CXIMAGE_FORMAT_TGA, #endif #if CXIMAGE_SUPPORT_PCX CXIMAGE_FORMAT_PCX, #endif #if CXIMAGE_SUPPORT_WBMP CXIMAGE_FORMAT_WBMP, #endif #if CXIMAGE_SUPPORT_WMF CXIMAGE_FORMAT_WMF, #endif #if CXIMAGE_SUPPORT_J2K CXIMAGE_FORMAT_J2K, #endif #if CXIMAGE_SUPPORT_JBG CXIMAGE_FORMAT_JBG, #endif #if CXIMAGE_SUPPORT_JP2 CXIMAGE_FORMAT_JP2, #endif #if CXIMAGE_SUPPORT_JPC CXIMAGE_FORMAT_JPC, #endif #if CXIMAGE_SUPPORT_PGX CXIMAGE_FORMAT_PGX, #endif #if CXIMAGE_SUPPORT_PNM CXIMAGE_FORMAT_PNM, #endif #if CXIMAGE_SUPPORT_RAS CXIMAGE_FORMAT_RAS, #endif CMAX_IMAGE_FORMATS }; ///////////////////////////////////////////////////////////////////////////// // CxImage class ///////////////////////////////////////////////////////////////////////////// class DLL_EXP CxImage { //extensible information collector typedef struct tagCxImageInfo { DWORD dwEffWidth; ///< DWORD aligned scan line width BYTE* pImage; ///< THE IMAGE BITS CxImage* pGhost; ///< if this is a ghost, pGhost points to the body CxImage* pParent; ///< if this is a layer, pParent points to the body DWORD dwType; ///< original image format char szLastError[256]; ///< debugging long nProgress; ///< monitor long nEscape; ///< escape long nBkgndIndex; ///< used for GIF, PNG, MNG RGBQUAD nBkgndColor; ///< used for RGB transparency BYTE nQuality; ///< used for JPEG BYTE nJpegScale; ///< used for JPEG [ignacio] long nFrame; ///< used for TIF, GIF, MNG : actual frame long nNumFrames; ///< used for TIF, GIF, MNG : total number of frames DWORD dwFrameDelay; ///< used for GIF, MNG long xDPI; ///< horizontal resolution long yDPI; ///< vertical resolution RECT rSelectionBox; ///< bounding rectangle BYTE nAlphaMax; ///< max opacity (fade) bool bAlphaPaletteEnabled; ///< true if alpha values in the palette are enabled. bool bEnabled; ///< enables the painting functions long xOffset; long yOffset; DWORD dwCodecOpt[CMAX_IMAGE_FORMATS]; ///< for GIF, TIF : 0=def.1=unc,2=fax3,3=fax4,4=pack,5=jpg RGBQUAD last_c; ///< for GetNearestIndex optimization BYTE last_c_index; bool last_c_isvalid; long nNumLayers; DWORD dwFlags; ///< 0x??00000 = reserved, 0x00??0000 = blend mode, 0x0000???? = layer id - user flags } CXIMAGEINFO; public: //public structures struct rgb_color { BYTE r,g,b; }; #if CXIMAGE_SUPPORT_WINDOWS // <VATI> text placement data // members must be initialized with the InitTextInfo(&this) function. typedef struct tagCxTextInfo { TCHAR text[4096]; ///< text (char -> TCHAR for UNICODE [Cesar M]) LOGFONT lfont; ///< font and codepage data COLORREF fcolor; ///< foreground color long align; ///< DT_CENTER, DT_RIGHT, DT_LEFT aligment for multiline text BYTE opaque; ///< text has background or hasn't. Default is true. ///< data for background (ignored if .opaque==FALSE) COLORREF bcolor; ///< background color float b_opacity; ///< opacity value for background between 0.0-1.0 Default is 0. (opaque) BYTE b_outline; ///< outline width for background (zero: no outline) BYTE b_round; ///< rounding radius for background rectangle. % of the height, between 0-50. Default is 10. ///< (backgr. always has a frame: width = 3 pixel + 10% of height by default.) } CXTEXTINFO; #endif public: /** \addtogroup Constructors */ //@{ CxImage(DWORD imagetype = 0); CxImage(DWORD dwWidth, DWORD dwHeight, DWORD wBpp, DWORD imagetype = 0); CxImage(const CxImage &src, bool copypixels = true, bool copyselection = true, bool copyalpha = true); CxImage(const TCHAR * filename, DWORD imagetype); // For UNICODE support: char -> TCHAR CxImage(FILE * stream, DWORD imagetype); CxImage(CxFile * stream, DWORD imagetype); CxImage(BYTE * buffer, DWORD size, DWORD imagetype); virtual ~CxImage() { Destroy(); }; CxImage& operator = (const CxImage&); //@} /** \addtogroup Initialization */ //@{ void* Create(DWORD dwWidth, DWORD dwHeight, DWORD wBpp, DWORD imagetype = 0); bool Destroy(); void Clear(BYTE bval=0); void Copy(const CxImage &src, bool copypixels = true, bool copyselection = true, bool copyalpha = true); bool Transfer(CxImage &from); bool CreateFromArray(BYTE* pArray,DWORD dwWidth,DWORD dwHeight,DWORD dwBitsperpixel, DWORD dwBytesperline, bool bFlipImage); bool CreateFromMatrix(BYTE** ppMatrix,DWORD dwWidth,DWORD dwHeight,DWORD dwBitsperpixel, DWORD dwBytesperline, bool bFlipImage); void FreeMemory(void* memblock); //@} /** \addtogroup Attributes */ //@{ long GetSize(); BYTE* GetBits(DWORD row = 0); BYTE GetColorType(); void* GetDIB() const; DWORD GetHeight() const; DWORD GetWidth() const; DWORD GetEffWidth() const; DWORD GetNumColors() const; WORD GetBpp() const; DWORD GetType() const; const char* GetLastError(); const TCHAR* GetVersion(); const float GetVersionNumber(); DWORD GetFrameDelay() const; void SetFrameDelay(DWORD d); void GetOffset(long *x,long *y); void SetOffset(long x,long y); BYTE GetJpegQuality() const; void SetJpegQuality(BYTE q); BYTE GetJpegScale() const; void SetJpegScale(BYTE q); long GetXDPI() const; long GetYDPI() const; void SetXDPI(long dpi); void SetYDPI(long dpi); DWORD GetClrImportant() const; void SetClrImportant(DWORD ncolors = 0); long GetProgress() const; long GetEscape() const; void SetProgress(long p); void SetEscape(long i); long GetTransIndex() const; RGBQUAD GetTransColor(); void SetTransIndex(long idx); void SetTransColor(RGBQUAD rgb); bool IsTransparent() const; DWORD GetCodecOption(DWORD imagetype = 0); bool SetCodecOption(DWORD opt, DWORD imagetype = 0); DWORD GetFlags() const; void SetFlags(DWORD flags, bool bLockReservedFlags = true); //void* GetUserData() const {return info.pUserData;} //void SetUserData(void* pUserData) {info.pUserData = pUserData;} //@} /** \addtogroup Palette * These functions have no effects on RGB images and in this case the returned value is always 0. * @{ */ bool IsGrayScale(); bool IsIndexed() const; bool IsSamePalette(CxImage &img, bool bCheckAlpha = true); DWORD GetPaletteSize(); RGBQUAD* GetPalette() const; RGBQUAD GetPaletteColor(BYTE idx); bool GetPaletteColor(BYTE i, BYTE* r, BYTE* g, BYTE* b); BYTE GetNearestIndex(RGBQUAD c); void BlendPalette(COLORREF cr,long perc); void SetGrayPalette(); void SetPalette(DWORD n, BYTE *r, BYTE *g, BYTE *b); void SetPalette(RGBQUAD* pPal,DWORD nColors=256); void SetPalette(rgb_color *rgb,DWORD nColors=256); void SetPaletteColor(BYTE idx, BYTE r, BYTE g, BYTE b, BYTE alpha=0); void SetPaletteColor(BYTE idx, RGBQUAD c); void SetPaletteColor(BYTE idx, COLORREF cr); void SwapIndex(BYTE idx1, BYTE idx2); void SetStdPalette(); //@} /** \addtogroup Pixel */ //@{ bool IsInside(long x, long y); bool IsTransparent(long x,long y); RGBQUAD GetPixelColor(long x,long y, bool bGetAlpha = true); BYTE GetPixelIndex(long x,long y); BYTE GetPixelGray(long x, long y); void SetPixelColor(long x,long y,RGBQUAD c, bool bSetAlpha = false); void SetPixelColor(long x,long y,COLORREF cr); void SetPixelIndex(long x,long y,BYTE i); void DrawLine(int StartX, int EndX, int StartY, int EndY, RGBQUAD color, bool bSetAlpha=false); void DrawLine(int StartX, int EndX, int StartY, int EndY, COLORREF cr); void BlendPixelColor(long x,long y,RGBQUAD c, float blend, bool bSetAlpha = false); //@} protected: /** \addtogroup Protected */ //@{ BYTE BlindGetPixelIndex(const long x,const long y); RGBQUAD BlindGetPixelColor(const long x,const long y); void *BlindGetPixelPointer(const long x,const long y); //@} public: #if CXIMAGE_SUPPORT_INTERPOLATION /** \addtogroup Interpolation */ //@{ //overflow methods: enum OverflowMethod { OM_COLOR=1, OM_BACKGROUND=2, OM_TRANSPARENT=3, OM_WRAP=4, OM_REPEAT=5, OM_MIRROR=6 }; void OverflowCoordinates(float &x, float &y, OverflowMethod const ofMethod); void OverflowCoordinates(long &x, long &y, OverflowMethod const ofMethod); RGBQUAD GetPixelColorWithOverflow(long x, long y, OverflowMethod const ofMethod=OM_BACKGROUND, RGBQUAD* const rplColor=0); //interpolation methods: enum InterpolationMethod { IM_NEAREST_NEIGHBOUR=1, IM_BILINEAR =2, IM_BSPLINE =3, IM_BICUBIC =4, IM_BICUBIC2 =5, IM_LANCZOS =6, IM_BOX =7, IM_HERMITE =8, IM_HAMMING =9, IM_SINC =10, IM_BLACKMAN =11, IM_BESSEL =12, IM_GAUSSIAN =13, IM_QUADRATIC =14, IM_MITCHELL =15, IM_CATROM =16 }; RGBQUAD GetPixelColorInterpolated(float x,float y, InterpolationMethod const inMethod=IM_BILINEAR, OverflowMethod const ofMethod=OM_BACKGROUND, RGBQUAD* const rplColor=0); RGBQUAD GetAreaColorInterpolated(float const xc, float const yc, float const w, float const h, InterpolationMethod const inMethod, OverflowMethod const ofMethod=OM_BACKGROUND, RGBQUAD* const rplColor=0); //@} protected: /** \addtogroup Protected */ //@{ void AddAveragingCont(RGBQUAD const &color, float const surf, float &rr, float &gg, float &bb, float &aa); //@} /** \addtogroup Kernels */ //@{ public: static float KernelBSpline(const float x); static float KernelLinear(const float t); static float KernelCubic(const float t); static float KernelGeneralizedCubic(const float t, const float a=-1); static float KernelLanczosSinc(const float t, const float r = 3); static float KernelBox(const float x); static float KernelHermite(const float x); static float KernelHamming(const float x); static float KernelSinc(const float x); static float KernelBlackman(const float x); static float KernelBessel_J1(const float x); static float KernelBessel_P1(const float x); static float KernelBessel_Q1(const float x); static float KernelBessel_Order1(float x); static float KernelBessel(const float x); static float KernelGaussian(const float x); static float KernelQuadratic(const float x); static float KernelMitchell(const float x); static float KernelCatrom(const float x); //@} #endif //CXIMAGE_SUPPORT_INTERPOLATION /** \addtogroup Painting */ //@{ #if CXIMAGE_SUPPORT_WINCE long Blt(HDC pDC, long x=0, long y=0); #endif #if CXIMAGE_SUPPORT_WINDOWS HBITMAP MakeBitmap(HDC hdc = NULL); HANDLE CopyToHandle(); bool CreateFromHANDLE(HANDLE hMem); //Windows objects (clipboard) bool CreateFromHBITMAP(HBITMAP hbmp, HPALETTE hpal=0); //Windows resource bool CreateFromHICON(HICON hico); long Draw(HDC hdc, long x=0, long y=0, long cx = -1, long cy = -1, RECT* pClipRect = 0, bool bSmooth = false); long Draw(HDC hdc, const RECT& rect, RECT* pClipRect=NULL, bool bSmooth = false); long Stretch(HDC hdc, long xoffset, long yoffset, long xsize, long ysize, DWORD dwRop = SRCCOPY); long Stretch(HDC hdc, const RECT& rect, DWORD dwRop = SRCCOPY); long Tile(HDC hdc, RECT *rc); long Draw2(HDC hdc, long x=0, long y=0, long cx = -1, long cy = -1); long Draw2(HDC hdc, const RECT& rect); //long DrawString(HDC hdc, long x, long y, const char* text, RGBQUAD color, const char* font, long lSize=0, long lWeight=400, BYTE bItalic=0, BYTE bUnderline=0, bool bSetAlpha=false); long DrawString(HDC hdc, long x, long y, const TCHAR* text, RGBQUAD color, const TCHAR* font, long lSize=0, long lWeight=400, BYTE bItalic=0, BYTE bUnderline=0, bool bSetAlpha=false); // <VATI> extensions long DrawStringEx(HDC hdc, long x, long y, CXTEXTINFO *pTextType, bool bSetAlpha=false ); void InitTextInfo( CXTEXTINFO *txt ); #endif //CXIMAGE_SUPPORT_WINDOWS //@} // file operations #if CXIMAGE_SUPPORT_DECODE /** \addtogroup Decode */ //@{ #ifdef WIN32 //bool Load(LPCWSTR filename, DWORD imagetype=0); bool LoadResource(HRSRC hRes, DWORD imagetype, HMODULE hModule=NULL); #endif // For UNICODE support: char -> TCHAR bool Load(const TCHAR* filename, DWORD imagetype=0); //bool Load(const char * filename, DWORD imagetype=0); bool Decode(FILE * hFile, DWORD imagetype); bool Decode(CxFile * hFile, DWORD imagetype); bool Decode(BYTE * buffer, DWORD size, DWORD imagetype); //@} #endif //CXIMAGE_SUPPORT_DECODE #if CXIMAGE_SUPPORT_ENCODE protected: /** \addtogroup Protected */ //@{ bool EncodeSafeCheck(CxFile *hFile); //@} public: /** \addtogroup Encode */ //@{ #ifdef WIN32 //bool Save(LPCWSTR filename, DWORD imagetype=0); #endif // For UNICODE support: char -> TCHAR bool Save(const TCHAR* filename, DWORD imagetype); //bool Save(const char * filename, DWORD imagetype=0); bool Encode(FILE * hFile, DWORD imagetype); bool Encode(CxFile * hFile, DWORD imagetype); bool Encode(CxFile * hFile, CxImage ** pImages, int pagecount, DWORD imagetype); bool Encode(FILE *hFile, CxImage ** pImages, int pagecount, DWORD imagetype); bool Encode(BYTE * &buffer, long &size, DWORD imagetype); bool Encode2RGBA(CxFile *hFile); bool Encode2RGBA(BYTE * &buffer, long &size); //@} #endif //CXIMAGE_SUPPORT_ENCODE /** \addtogroup Attributes */ //@{ //misc. bool IsValid() const; bool IsEnabled() const; void Enable(bool enable=true); // frame operations long GetNumFrames() const; long GetFrame() const; void SetFrame(long nFrame); //@} #if CXIMAGE_SUPPORT_BASICTRANSFORMATIONS /** \addtogroup BasicTransformations */ //@{ bool GrayScale(); bool Flip(); bool Mirror(); bool Negative(); bool RotateLeft(CxImage* iDst = NULL); bool RotateRight(CxImage* iDst = NULL); //@} #endif //CXIMAGE_SUPPORT_BASICTRANSFORMATIONS #if CXIMAGE_SUPPORT_TRANSFORMATION /** \addtogroup Transformations */ //@{ // image operations bool Rotate(float angle, CxImage* iDst = NULL); bool Rotate2(float angle, CxImage *iDst = NULL, InterpolationMethod inMethod=IM_BILINEAR, OverflowMethod ofMethod=OM_BACKGROUND, RGBQUAD *replColor=0, bool const optimizeRightAngles=true, bool const bKeepOriginalSize=false); bool Rotate180(CxImage* iDst = NULL); bool Resample(long newx, long newy, int mode = 1, CxImage* iDst = NULL); bool Resample2(long newx, long newy, InterpolationMethod const inMethod=IM_BICUBIC2, OverflowMethod const ofMethod=OM_REPEAT, CxImage* const iDst = NULL, bool const disableAveraging=false); bool DecreaseBpp(DWORD nbit, bool errordiffusion, RGBQUAD* ppal = 0, DWORD clrimportant = 0); bool IncreaseBpp(DWORD nbit); bool Dither(long method = 0); bool Crop(long left, long top, long right, long bottom, CxImage* iDst = NULL); bool Crop(const RECT& rect, CxImage* iDst = NULL); bool CropRotatedRectangle( long topx, long topy, long width, long height, float angle, CxImage* iDst = NULL); bool Skew(float xgain, float ygain, long xpivot=0, long ypivot=0, bool bEnableInterpolation = false); bool Expand(long left, long top, long right, long bottom, RGBQUAD canvascolor, CxImage* iDst = 0); bool Expand(long newx, long newy, RGBQUAD canvascolor, CxImage* iDst = 0); bool Thumbnail(long newx, long newy, RGBQUAD canvascolor, CxImage* iDst = 0); bool CircleTransform(int type,long rmax=0,float Koeff=1.0f); bool RedEyeRemove(); bool QIShrink(long newx, long newy, CxImage* const iDst = NULL); //@} #endif //CXIMAGE_SUPPORT_TRANSFORMATION #if CXIMAGE_SUPPORT_DSP /** \addtogroup DSP */ //@{ bool Contour(); bool HistogramStretch(long method = 0); bool HistogramEqualize(); bool HistogramNormalize(); bool HistogramRoot(); bool HistogramLog(); long Histogram(long* red, long* green = 0, long* blue = 0, long* gray = 0, long colorspace = 0); bool Jitter(long radius=2); bool Repair(float radius = 0.25f, long niterations = 1, long colorspace = 0); bool Combine(CxImage* r,CxImage* g,CxImage* b,CxImage* a, long colorspace = 0); bool FFT2(CxImage* srcReal, CxImage* srcImag, CxImage* dstReal, CxImage* dstImag, long direction = 1, bool bForceFFT = true, bool bMagnitude = true); bool Noise(long level); bool Median(long Ksize=3); bool Gamma(float gamma); bool ShiftRGB(long r, long g, long b); bool Threshold(BYTE level); bool Colorize(BYTE hue, BYTE sat, float blend = 1.0f); bool Light(long brightness, long contrast = 0); float Mean(); bool Filter(long* kernel, long Ksize, long Kfactor, long Koffset); bool Erode(long Ksize=2); bool Dilate(long Ksize=2); bool Edge(long Ksize=2); void HuePalette(float correction=1); enum ImageOpType { OpAdd, OpAnd, OpXor, OpOr, OpMask, OpSrcCopy, OpDstCopy, OpSub, OpSrcBlend, OpScreen }; void Mix(CxImage & imgsrc2, ImageOpType op, long lXOffset = 0, long lYOffset = 0, bool bMixAlpha = false); void MixFrom(CxImage & imagesrc2, long lXOffset, long lYOffset); bool UnsharpMask(float radius = 5.0, float amount = 0.5, int threshold = 0); bool Lut(BYTE* pLut); bool Lut(BYTE* pLutR, BYTE* pLutG, BYTE* pLutB, BYTE* pLutA = 0); //@} protected: /** \addtogroup Protected */ //@{ bool IsPowerof2(long x); bool FFT(int dir,int m,double *x,double *y); bool DFT(int dir,long m,double *x1,double *y1,double *x2,double *y2); bool RepairChannel(CxImage *ch, float radius); // <nipper> int gen_convolve_matrix (float radius, float **cmatrix_p); float* gen_lookup_table (float *cmatrix, int cmatrix_length); void blur_line (float *ctable, float *cmatrix, int cmatrix_length, BYTE* cur_col, BYTE* dest_col, int y, long bytes); //@} public: /** \addtogroup ColorSpace */ //@{ bool SplitRGB(CxImage* r,CxImage* g,CxImage* b); bool SplitYUV(CxImage* y,CxImage* u,CxImage* v); bool SplitHSL(CxImage* h,CxImage* s,CxImage* l); bool SplitYIQ(CxImage* y,CxImage* i,CxImage* q); bool SplitXYZ(CxImage* x,CxImage* y,CxImage* z); bool SplitCMYK(CxImage* c,CxImage* m,CxImage* y,CxImage* k); static RGBQUAD HSLtoRGB(COLORREF cHSLColor); static RGBQUAD RGBtoHSL(RGBQUAD lRGBColor); static RGBQUAD HSLtoRGB(RGBQUAD lHSLColor); static RGBQUAD YUVtoRGB(RGBQUAD lYUVColor); static RGBQUAD RGBtoYUV(RGBQUAD lRGBColor); static RGBQUAD YIQtoRGB(RGBQUAD lYIQColor); static RGBQUAD RGBtoYIQ(RGBQUAD lRGBColor); static RGBQUAD XYZtoRGB(RGBQUAD lXYZColor); static RGBQUAD RGBtoXYZ(RGBQUAD lRGBColor); #endif //CXIMAGE_SUPPORT_DSP static RGBQUAD RGBtoRGBQUAD(COLORREF cr); static COLORREF RGBQUADtoRGB (RGBQUAD c); //@} #if CXIMAGE_SUPPORT_SELECTION /** \addtogroup Selection */ //@{ bool SelectionClear(); bool SelectionCreate(); bool SelectionDelete(); bool SelectionInvert(); bool SelectionAddRect(RECT r); bool SelectionAddEllipse(RECT r); bool SelectionAddPolygon(POINT *points, long npoints); bool SelectionAddColor(RGBQUAD c); bool SelectionAddPixel(int x, int y); bool SelectionCopy(CxImage &from); bool SelectionIsInside(long x, long y); bool SelectionIsValid(); void SelectionGetBox(RECT& r); bool SelectionToHRGN(HRGN& region); bool SelectionSplit(CxImage *dest); //@} #endif //CXIMAGE_SUPPORT_SELECTION #if CXIMAGE_SUPPORT_ALPHA /** \addtogroup Alpha */ //@{ void AlphaClear(); void AlphaCreate(); void AlphaDelete(); void AlphaInvert(); bool AlphaMirror(); bool AlphaFlip(); bool AlphaCopy(CxImage &from); bool AlphaSplit(CxImage *dest); void AlphaStrip(); void AlphaSet(BYTE level); bool AlphaSet(CxImage &from); void AlphaSet(const long x,const long y,const BYTE level); BYTE AlphaGet(const long x,const long y); BYTE AlphaGetMax() const; void AlphaSetMax(BYTE nAlphaMax); bool AlphaIsValid(); BYTE* AlphaGetPointer(const long x = 0,const long y = 0); void AlphaPaletteClear(); void AlphaPaletteEnable(bool enable=true); bool AlphaPaletteIsEnabled(); bool AlphaPaletteIsValid(); bool AlphaPaletteSplit(CxImage *dest); //@} protected: /** \addtogroup Protected */ //@{ BYTE BlindAlphaGet(const long x,const long y); //@} #endif //CXIMAGE_SUPPORT_ALPHA public: #if CXIMAGE_SUPPORT_LAYERS /** \addtogroup Layers */ //@{ bool LayerCreate(long position = -1); bool LayerDelete(long position = -1); void LayerDeleteAll(); CxImage* GetLayer(long position); CxImage* GetParent() const; long GetNumLayers() const; //@} #endif //CXIMAGE_SUPPORT_LAYERS protected: /** \addtogroup Protected */ //@{ void Startup(DWORD imagetype = 0); void CopyInfo(const CxImage &src); void Ghost(CxImage *src); void RGBtoBGR(BYTE *buffer, int length); static float HueToRGB(float n1,float n2, float hue); void Bitfield2RGB(BYTE *src, WORD redmask, WORD greenmask, WORD bluemask, BYTE bpp); static int CompareColors(const void *elem1, const void *elem2); void* pDib; //contains the header, the palette, the pixels BITMAPINFOHEADER head; //standard header CXIMAGEINFO info; //extended information BYTE* pSelection; //selected region BYTE* pAlpha; //alpha channel CxImage** pLayers; //generic layers //@} }; //////////////////////////////////////////////////////////////////////////// #endif // !defined(__CXIMAGE_H)
zzh-project-test
branches/ThumbViewer/include/ximage.h
C++
asf20
24,080
#if !defined(__ximadefs_h) #define __ximadefs_h #include "ximacfg.h" #if defined(_AFXDLL)||defined(_USRDLL) #define DLL_EXP __declspec(dllexport) #elif defined(_MSC_VER)&&(_MSC_VER<1200) #define DLL_EXP __declspec(dllimport) #else #define DLL_EXP #endif #if CXIMAGE_SUPPORT_JP2 || CXIMAGE_SUPPORT_JPC || CXIMAGE_SUPPORT_PGX || CXIMAGE_SUPPORT_PNM || CXIMAGE_SUPPORT_RAS #define CXIMAGE_SUPPORT_JASPER 1 #else #define CXIMAGE_SUPPORT_JASPER 0 #endif #if CXIMAGE_SUPPORT_DSP #undef CXIMAGE_SUPPORT_TRANSFORMATION #define CXIMAGE_SUPPORT_TRANSFORMATION 1 #endif #if CXIMAGE_SUPPORT_TRANSFORMATION || CXIMAGE_SUPPORT_TIF || CXIMAGE_SUPPORT_TGA || CXIMAGE_SUPPORT_BMP || CXIMAGE_SUPPORT_WINDOWS #define CXIMAGE_SUPPORT_BASICTRANSFORMATIONS 1 #endif #if CXIMAGE_SUPPORT_DSP || CXIMAGE_SUPPORT_TRANSFORMATION #undef CXIMAGE_SUPPORT_INTERPOLATION #define CXIMAGE_SUPPORT_INTERPOLATION 1 #endif #if CXIMAGE_SUPPORT_WINCE #undef CXIMAGE_SUPPORT_WMF #define CXIMAGE_SUPPORT_WMF 0 #undef CXIMAGE_SUPPORT_WINDOWS #define CXIMAGE_SUPPORT_WINDOWS 0 #endif #ifndef WIN32 #undef CXIMAGE_SUPPORT_WINDOWS #define CXIMAGE_SUPPORT_WINDOWS 0 #endif #ifndef min #define min(a,b) (((a)<(b))?(a):(b)) #endif #ifndef max #define max(a,b) (((a)>(b))?(a):(b)) #endif #ifndef PI #define PI 3.141592653589793f #endif #ifdef WIN32 #include <windows.h> #include <tchar.h> #endif #include <stdio.h> #include <math.h> #ifdef __BORLANDC__ #ifndef _COMPLEX_DEFINED typedef struct tagcomplex { double x,y; } _complex; #endif #define _cabs(c) sqrt(c.x*c.x+c.y*c.y) #endif #ifndef WIN32 #include <stdlib.h> #include <string.h> #include <ctype.h> typedef unsigned char BYTE; typedef unsigned short WORD; typedef unsigned long DWORD; typedef unsigned int UINT; typedef DWORD COLORREF; typedef unsigned int HANDLE; typedef void* HRGN; #ifndef BOOL #define BOOL bool #endif #ifndef TRUE #define TRUE true #endif #ifndef FALSE #define FALSE false #endif #ifndef TCHAR #define TCHAR char #define _T #endif typedef struct tagRECT { long left; long top; long right; long bottom; } RECT; typedef struct tagPOINT { long x; long y; } POINT; typedef struct tagRGBQUAD { BYTE rgbBlue; BYTE rgbGreen; BYTE rgbRed; BYTE rgbReserved; } RGBQUAD; #pragma pack(1) typedef struct tagBITMAPINFOHEADER{ DWORD biSize; long biWidth; long biHeight; WORD biPlanes; WORD biBitCount; DWORD biCompression; DWORD biSizeImage; long biXPelsPerMeter; long biYPelsPerMeter; DWORD biClrUsed; DWORD biClrImportant; } BITMAPINFOHEADER; typedef struct tagBITMAPFILEHEADER { WORD bfType; DWORD bfSize; WORD bfReserved1; WORD bfReserved2; DWORD bfOffBits; } BITMAPFILEHEADER; typedef struct tagBITMAPCOREHEADER { DWORD bcSize; WORD bcWidth; WORD bcHeight; WORD bcPlanes; WORD bcBitCount; } BITMAPCOREHEADER; typedef struct tagRGBTRIPLE { BYTE rgbtBlue; BYTE rgbtGreen; BYTE rgbtRed; } RGBTRIPLE; #pragma pack() #define BI_RGB 0L #define BI_RLE8 1L #define BI_RLE4 2L #define BI_BITFIELDS 3L #define GetRValue(rgb) ((BYTE)(rgb)) #define GetGValue(rgb) ((BYTE)(((WORD)(rgb)) >> 8)) #define GetBValue(rgb) ((BYTE)((rgb)>>16)) #define RGB(r,g,b) ((COLORREF)(((BYTE)(r)|((WORD)((BYTE)(g))<<8))|(((DWORD)(BYTE)(b))<<16))) #ifndef _COMPLEX_DEFINED typedef struct tagcomplex { double x,y; } _complex; #endif #define _cabs(c) sqrt(c.x*c.x+c.y*c.y) #endif #endif //__ximadefs
zzh-project-test
branches/ThumbViewer/include/ximadef.h
C
asf20
3,772
#if !defined(__ximaCFG_h) #define __ximaCFG_h ///////////////////////////////////////////////////////////////////////////// // CxImage supported features #define CXIMAGE_SUPPORT_ALPHA 1 #define CXIMAGE_SUPPORT_SELECTION 1 #define CXIMAGE_SUPPORT_TRANSFORMATION 1 #define CXIMAGE_SUPPORT_DSP 1 #define CXIMAGE_SUPPORT_LAYERS 1 #define CXIMAGE_SUPPORT_INTERPOLATION 1 #define CXIMAGE_SUPPORT_DECODE 1 #define CXIMAGE_SUPPORT_ENCODE 1 //<vho><T.Peck> #define CXIMAGE_SUPPORT_WINDOWS 1 #define CXIMAGE_SUPPORT_WINCE 0 //<T.Peck> ///////////////////////////////////////////////////////////////////////////// // CxImage supported formats #define CXIMAGE_SUPPORT_BMP 1 #define CXIMAGE_SUPPORT_GIF 1 #define CXIMAGE_SUPPORT_JPG 1 #define CXIMAGE_SUPPORT_PNG 1 #define CXIMAGE_SUPPORT_MNG 0 #define CXIMAGE_SUPPORT_ICO 1 #define CXIMAGE_SUPPORT_TIF 1 #define CXIMAGE_SUPPORT_TGA 1 #define CXIMAGE_SUPPORT_PCX 1 #define CXIMAGE_SUPPORT_WBMP 1 #define CXIMAGE_SUPPORT_WMF 1 #define CXIMAGE_SUPPORT_J2K 0 // Beta, use JP2 #define CXIMAGE_SUPPORT_JBG 0 // GPL'd see ../jbig/copying.txt & ../jbig/patents.htm #define CXIMAGE_SUPPORT_JP2 1 #define CXIMAGE_SUPPORT_JPC 1 #define CXIMAGE_SUPPORT_PGX 1 #define CXIMAGE_SUPPORT_PNM 1 #define CXIMAGE_SUPPORT_RAS 1 ///////////////////////////////////////////////////////////////////////////// #define CXIMAGE_MAX_MEMORY 256000000 #define CXIMAGE_ERR_NOFILE "null file handler" #define CXIMAGE_ERR_NOIMAGE "null image!!!" ///////////////////////////////////////////////////////////////////////////// //color to grey mapping <H. Muelner> <jurgene> //#define RGB2GRAY(r,g,b) (((b)*114 + (g)*587 + (r)*299)/1000) #define RGB2GRAY(r,g,b) (((b)*117 + (g)*601 + (r)*306) >> 10) #endif
zzh-project-test
branches/ThumbViewer/include/ximacfg.h
C
asf20
1,805
#if !defined(__xiofile_h) #define __xiofile_h #include "xfile.h" class DLL_EXP CxIOFile : public CxFile { public: CxIOFile(FILE* fp = NULL) { m_fp = fp; m_bCloseFile = (bool)(fp==0); } ~CxIOFile() { Close(); } ////////////////////////////////////////////////////////// bool Open(const char *filename, const char *mode) { if (m_fp) return false; // Can't re-open without closing first m_fp = fopen(filename, mode); if (!m_fp) return false; m_bCloseFile = true; return true; } ////////////////////////////////////////////////////////// virtual bool Close() { int iErr = 0; if ( (m_fp) && (m_bCloseFile) ){ iErr = fclose(m_fp); m_fp = NULL; } return (bool)(iErr==0); } ////////////////////////////////////////////////////////// virtual size_t Read(void *buffer, size_t size, size_t count) { if (!m_fp) return 0; return fread(buffer, size, count, m_fp); } ////////////////////////////////////////////////////////// virtual size_t Write(const void *buffer, size_t size, size_t count) { if (!m_fp) return 0; return fwrite(buffer, size, count, m_fp); } ////////////////////////////////////////////////////////// virtual bool Seek(long offset, int origin) { if (!m_fp) return false; return (bool)(fseek(m_fp, offset, origin) == 0); } ////////////////////////////////////////////////////////// virtual long Tell() { if (!m_fp) return 0; return ftell(m_fp); } ////////////////////////////////////////////////////////// virtual long Size() { if (!m_fp) return -1; long pos,size; pos = ftell(m_fp); fseek(m_fp, 0, SEEK_END); size = ftell(m_fp); fseek(m_fp, pos,SEEK_SET); return size; } ////////////////////////////////////////////////////////// virtual bool Flush() { if (!m_fp) return false; return (bool)(fflush(m_fp) == 0); } ////////////////////////////////////////////////////////// virtual bool Eof() { if (!m_fp) return true; return (bool)(feof(m_fp) != 0); } ////////////////////////////////////////////////////////// virtual long Error() { if (!m_fp) return -1; return ferror(m_fp); } ////////////////////////////////////////////////////////// virtual bool PutC(unsigned char c) { if (!m_fp) return false; return (bool)(fputc(c, m_fp) == c); } ////////////////////////////////////////////////////////// virtual long GetC() { if (!m_fp) return EOF; return getc(m_fp); } ////////////////////////////////////////////////////////// protected: FILE *m_fp; bool m_bCloseFile; }; #endif
zzh-project-test
branches/ThumbViewer/include/xiofile.h
C++
asf20
2,624
#include "stdafx.h" #include "mainfrm.h" #include "FileView.h" #include "Resource.h" #include "GoogleCodeTest.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ///////////////////////////////////////////////////////////////////////////// // CFileView CFileView::CFileView() { } CFileView::~CFileView() { } BEGIN_MESSAGE_MAP(CFileView, CDockablePane) ON_WM_CREATE() ON_WM_SIZE() ON_WM_CONTEXTMENU() ON_COMMAND(ID_PROPERTIES, OnProperties) ON_COMMAND(ID_OPEN, OnFileOpen) ON_COMMAND(ID_OPEN_WITH, OnFileOpenWith) ON_COMMAND(ID_DUMMY_COMPILE, OnDummyCompile) ON_COMMAND(ID_EDIT_CUT, OnEditCut) ON_COMMAND(ID_EDIT_COPY, OnEditCopy) ON_COMMAND(ID_EDIT_CLEAR, OnEditClear) ON_WM_PAINT() ON_WM_SETFOCUS() END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CWorkspaceBar message handlers int CFileView::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CDockablePane::OnCreate(lpCreateStruct) == -1) return -1; CRect rectDummy; rectDummy.SetRectEmpty(); // Create view: const DWORD dwViewStyle = WS_CHILD | WS_VISIBLE | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS; if (!m_wndFileView.Create(dwViewStyle, rectDummy, this, 4)) { TRACE0("Failed to create file view\n"); return -1; // fail to create } // Load view images: m_FileViewImages.Create(IDB_FILE_VIEW, 16, 0, RGB(255, 0, 255)); m_wndFileView.SetImageList(&m_FileViewImages, TVSIL_NORMAL); m_wndToolBar.Create(this, AFX_DEFAULT_TOOLBAR_STYLE, IDR_EXPLORER); m_wndToolBar.LoadToolBar(IDR_EXPLORER, 0, 0, TRUE /* Is locked */); OnChangeVisualStyle(); m_wndToolBar.SetPaneStyle(m_wndToolBar.GetPaneStyle() | CBRS_TOOLTIPS | CBRS_FLYBY); m_wndToolBar.SetPaneStyle(m_wndToolBar.GetPaneStyle() & ~(CBRS_GRIPPER | CBRS_SIZE_DYNAMIC | CBRS_BORDER_TOP | CBRS_BORDER_BOTTOM | CBRS_BORDER_LEFT | CBRS_BORDER_RIGHT)); m_wndToolBar.SetOwner(this); // All commands will be routed via this control , not via the parent frame: m_wndToolBar.SetRouteCommandsViaFrame(FALSE); // Fill in some static tree view data (dummy code, nothing magic here) FillFileView(); AdjustLayout(); return 0; } void CFileView::OnSize(UINT nType, int cx, int cy) { CDockablePane::OnSize(nType, cx, cy); AdjustLayout(); } void CFileView::FillFileView() { HTREEITEM hRoot = m_wndFileView.InsertItem(_T("FakeApp files"), 0, 0); m_wndFileView.SetItemState(hRoot, TVIS_BOLD, TVIS_BOLD); HTREEITEM hSrc = m_wndFileView.InsertItem(_T("FakeApp Source Files"), 0, 0, hRoot); m_wndFileView.InsertItem(_T("FakeApp.cpp"), 1, 1, hSrc); m_wndFileView.InsertItem(_T("FakeApp.rc"), 1, 1, hSrc); m_wndFileView.InsertItem(_T("FakeAppDoc.cpp"), 1, 1, hSrc); m_wndFileView.InsertItem(_T("FakeAppView.cpp"), 1, 1, hSrc); m_wndFileView.InsertItem(_T("MainFrm.cpp"), 1, 1, hSrc); m_wndFileView.InsertItem(_T("StdAfx.cpp"), 1, 1, hSrc); HTREEITEM hInc = m_wndFileView.InsertItem(_T("FakeApp Header Files"), 0, 0, hRoot); m_wndFileView.InsertItem(_T("FakeApp.h"), 2, 2, hInc); m_wndFileView.InsertItem(_T("FakeAppDoc.h"), 2, 2, hInc); m_wndFileView.InsertItem(_T("FakeAppView.h"), 2, 2, hInc); m_wndFileView.InsertItem(_T("Resource.h"), 2, 2, hInc); m_wndFileView.InsertItem(_T("MainFrm.h"), 2, 2, hInc); m_wndFileView.InsertItem(_T("StdAfx.h"), 2, 2, hInc); HTREEITEM hRes = m_wndFileView.InsertItem(_T("FakeApp Resource Files"), 0, 0, hRoot); m_wndFileView.InsertItem(_T("FakeApp.ico"), 2, 2, hRes); m_wndFileView.InsertItem(_T("FakeApp.rc2"), 2, 2, hRes); m_wndFileView.InsertItem(_T("FakeAppDoc.ico"), 2, 2, hRes); m_wndFileView.InsertItem(_T("FakeToolbar.bmp"), 2, 2, hRes); m_wndFileView.Expand(hRoot, TVE_EXPAND); m_wndFileView.Expand(hSrc, TVE_EXPAND); m_wndFileView.Expand(hInc, TVE_EXPAND); } void CFileView::OnContextMenu(CWnd* pWnd, CPoint point) { CTreeCtrl* pWndTree = (CTreeCtrl*) &m_wndFileView; ASSERT_VALID(pWndTree); if (pWnd != pWndTree) { CDockablePane::OnContextMenu(pWnd, point); return; } if (point != CPoint(-1, -1)) { // Select clicked item: CPoint ptTree = point; pWndTree->ScreenToClient(&ptTree); UINT flags = 0; HTREEITEM hTreeItem = pWndTree->HitTest(ptTree, &flags); if (hTreeItem != NULL) { pWndTree->SelectItem(hTreeItem); } } pWndTree->SetFocus(); theApp.GetContextMenuManager()->ShowPopupMenu(IDR_POPUP_EXPLORER, point.x, point.y, this, TRUE); } void CFileView::AdjustLayout() { if (GetSafeHwnd() == NULL) { return; } CRect rectClient; GetClientRect(rectClient); int cyTlb = m_wndToolBar.CalcFixedLayout(FALSE, TRUE).cy; m_wndToolBar.SetWindowPos(NULL, rectClient.left, rectClient.top, rectClient.Width(), cyTlb, SWP_NOACTIVATE | SWP_NOZORDER); m_wndFileView.SetWindowPos(NULL, rectClient.left + 1, rectClient.top + cyTlb + 1, rectClient.Width() - 2, rectClient.Height() - cyTlb - 2, SWP_NOACTIVATE | SWP_NOZORDER); } void CFileView::OnProperties() { AfxMessageBox(_T("Properties....")); } void CFileView::OnFileOpen() { // TODO: Add your command handler code here } void CFileView::OnFileOpenWith() { // TODO: Add your command handler code here } void CFileView::OnDummyCompile() { // TODO: Add your command handler code here } void CFileView::OnEditCut() { // TODO: Add your command handler code here } void CFileView::OnEditCopy() { // TODO: Add your command handler code here } void CFileView::OnEditClear() { // TODO: Add your command handler code here } void CFileView::OnPaint() { CPaintDC dc(this); // device context for painting CRect rectTree; m_wndFileView.GetWindowRect(rectTree); ScreenToClient(rectTree); rectTree.InflateRect(1, 1); dc.Draw3dRect(rectTree, ::GetSysColor(COLOR_3DSHADOW), ::GetSysColor(COLOR_3DSHADOW)); } void CFileView::OnSetFocus(CWnd* pOldWnd) { CDockablePane::OnSetFocus(pOldWnd); m_wndFileView.SetFocus(); } void CFileView::OnChangeVisualStyle() { m_wndToolBar.CleanUpLockedImages(); m_wndToolBar.LoadBitmap(theApp.m_bHiColorIcons ? IDB_EXPLORER_24 : IDR_EXPLORER, 0, 0, TRUE /* Locked */); m_FileViewImages.DeleteImageList(); UINT uiBmpId = theApp.m_bHiColorIcons ? IDB_FILE_VIEW_24 : IDB_FILE_VIEW; CBitmap bmp; if (!bmp.LoadBitmap(uiBmpId)) { TRACE(_T("Can't load bitmap: %x\n"), uiBmpId); ASSERT(FALSE); return; } BITMAP bmpObj; bmp.GetBitmap(&bmpObj); UINT nFlags = ILC_MASK; nFlags |= (theApp.m_bHiColorIcons) ? ILC_COLOR24 : ILC_COLOR4; m_FileViewImages.Create(16, bmpObj.bmHeight, nFlags, 0, 0); m_FileViewImages.Add(&bmp, RGB(255, 0, 255)); m_wndFileView.SetImageList(&m_FileViewImages, TVSIL_NORMAL); }
zzh-project-test
trunk/GoogleCodeTest/GoogleCodeTest/FileView.cpp
C++
asf20
6,831
#pragma once #include "ViewTree.h" class CFileViewToolBar : public CMFCToolBar { virtual void OnUpdateCmdUI(CFrameWnd* /*pTarget*/, BOOL bDisableIfNoHndler) { CMFCToolBar::OnUpdateCmdUI((CFrameWnd*) GetOwner(), bDisableIfNoHndler); } virtual BOOL AllowShowOnList() const { return FALSE; } }; class CFileView : public CDockablePane { // Construction public: CFileView(); void AdjustLayout(); void OnChangeVisualStyle(); // Attributes protected: CViewTree m_wndFileView; CImageList m_FileViewImages; CFileViewToolBar m_wndToolBar; protected: void FillFileView(); // Implementation public: virtual ~CFileView(); protected: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnContextMenu(CWnd* pWnd, CPoint point); afx_msg void OnProperties(); afx_msg void OnFileOpen(); afx_msg void OnFileOpenWith(); afx_msg void OnDummyCompile(); afx_msg void OnEditCut(); afx_msg void OnEditCopy(); afx_msg void OnEditClear(); afx_msg void OnPaint(); afx_msg void OnSetFocus(CWnd* pOldWnd); DECLARE_MESSAGE_MAP() };
zzh-project-test
trunk/GoogleCodeTest/GoogleCodeTest/FileView.h
C++
asf20
1,159
// GoogleCodeTestView.h : interface of the CGoogleCodeTestView class // #pragma once class CGoogleCodeTestView : public CView { protected: // create from serialization only CGoogleCodeTestView(); DECLARE_DYNCREATE(CGoogleCodeTestView) // Attributes public: CGoogleCodeTestDoc* GetDocument() const; // Operations public: // Overrides public: virtual void OnDraw(CDC* pDC); // overridden to draw this view virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); // Implementation public: virtual ~CGoogleCodeTestView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: afx_msg void OnFilePrintPreview(); afx_msg void OnRButtonUp(UINT nFlags, CPoint point); afx_msg void OnContextMenu(CWnd* pWnd, CPoint point); DECLARE_MESSAGE_MAP() }; #ifndef _DEBUG // debug version in GoogleCodeTestView.cpp inline CGoogleCodeTestDoc* CGoogleCodeTestView::GetDocument() const { return reinterpret_cast<CGoogleCodeTestDoc*>(m_pDocument); } #endif
zzh-project-test
trunk/GoogleCodeTest/GoogleCodeTest/GoogleCodeTestView.h
C++
asf20
1,290
#pragma once ///////////////////////////////////////////////////////////////////////////// // CViewTree window class CViewTree : public CTreeCtrl { // Construction public: CViewTree(); // Overrides protected: virtual BOOL OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult); // Implementation public: virtual ~CViewTree(); protected: DECLARE_MESSAGE_MAP() };
zzh-project-test
trunk/GoogleCodeTest/GoogleCodeTest/ViewTree.h
C++
asf20
397
// GoogleCodeTestView.cpp : implementation of the CGoogleCodeTestView class // #include "stdafx.h" // SHARED_HANDLERS can be defined in an ATL project implementing preview, thumbnail // and search filter handlers and allows sharing of document code with that project. #ifndef SHARED_HANDLERS #include "GoogleCodeTest.h" #endif #include "GoogleCodeTestDoc.h" #include "GoogleCodeTestView.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CGoogleCodeTestView IMPLEMENT_DYNCREATE(CGoogleCodeTestView, CView) BEGIN_MESSAGE_MAP(CGoogleCodeTestView, CView) // Standard printing commands ON_COMMAND(ID_FILE_PRINT, &CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, &CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, &CGoogleCodeTestView::OnFilePrintPreview) ON_WM_CONTEXTMENU() ON_WM_RBUTTONUP() END_MESSAGE_MAP() // CGoogleCodeTestView construction/destruction CGoogleCodeTestView::CGoogleCodeTestView() { // TODO: add construction code here } CGoogleCodeTestView::~CGoogleCodeTestView() { } BOOL CGoogleCodeTestView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return CView::PreCreateWindow(cs); } // CGoogleCodeTestView drawing void CGoogleCodeTestView::OnDraw(CDC* /*pDC*/) { CGoogleCodeTestDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: add draw code for native data here } // CGoogleCodeTestView printing void CGoogleCodeTestView::OnFilePrintPreview() { #ifndef SHARED_HANDLERS AFXPrintPreview(this); #endif } BOOL CGoogleCodeTestView::OnPreparePrinting(CPrintInfo* pInfo) { // default preparation return DoPreparePrinting(pInfo); } void CGoogleCodeTestView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add extra initialization before printing } void CGoogleCodeTestView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add cleanup after printing } void CGoogleCodeTestView::OnRButtonUp(UINT /* nFlags */, CPoint point) { ClientToScreen(&point); OnContextMenu(this, point); } void CGoogleCodeTestView::OnContextMenu(CWnd* /* pWnd */, CPoint point) { #ifndef SHARED_HANDLERS theApp.GetContextMenuManager()->ShowPopupMenu(IDR_POPUP_EDIT, point.x, point.y, this, TRUE); #endif } // CGoogleCodeTestView diagnostics #ifdef _DEBUG void CGoogleCodeTestView::AssertValid() const { CView::AssertValid(); } void CGoogleCodeTestView::Dump(CDumpContext& dc) const { CView::Dump(dc); } CGoogleCodeTestDoc* CGoogleCodeTestView::GetDocument() const // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CGoogleCodeTestDoc))); return (CGoogleCodeTestDoc*)m_pDocument; } #endif //_DEBUG // CGoogleCodeTestView message handlers
zzh-project-test
trunk/GoogleCodeTest/GoogleCodeTest/GoogleCodeTestView.cpp
C++
asf20
2,864
// stdafx.cpp : source file that includes just the standard includes // GoogleCodeTest.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
zzh-project-test
trunk/GoogleCodeTest/GoogleCodeTest/stdafx.cpp
C++
asf20
216
// ChildFrm.h : interface of the CChildFrame class // #pragma once class CChildFrame : public CMDIChildWndEx { DECLARE_DYNCREATE(CChildFrame) public: CChildFrame(); // Attributes public: // Operations public: // Overrides virtual BOOL PreCreateWindow(CREATESTRUCT& cs); // Implementation public: virtual ~CChildFrame(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif // Generated message map functions protected: DECLARE_MESSAGE_MAP() };
zzh-project-test
trunk/GoogleCodeTest/GoogleCodeTest/ChildFrm.h
C++
asf20
537
#pragma once class CPropertiesToolBar : public CMFCToolBar { public: virtual void OnUpdateCmdUI(CFrameWnd* /*pTarget*/, BOOL bDisableIfNoHndler) { CMFCToolBar::OnUpdateCmdUI((CFrameWnd*) GetOwner(), bDisableIfNoHndler); } virtual BOOL AllowShowOnList() const { return FALSE; } }; class CPropertiesWnd : public CDockablePane { // Construction public: CPropertiesWnd(); void AdjustLayout(); // Attributes public: void SetVSDotNetLook(BOOL bSet) { m_wndPropList.SetVSDotNetLook(bSet); m_wndPropList.SetGroupNameFullWidth(bSet); } protected: CFont m_fntPropList; CComboBox m_wndObjectCombo; CPropertiesToolBar m_wndToolBar; CMFCPropertyGridCtrl m_wndPropList; // Implementation public: virtual ~CPropertiesWnd(); protected: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnExpandAllProperties(); afx_msg void OnUpdateExpandAllProperties(CCmdUI* pCmdUI); afx_msg void OnSortProperties(); afx_msg void OnUpdateSortProperties(CCmdUI* pCmdUI); afx_msg void OnProperties1(); afx_msg void OnUpdateProperties1(CCmdUI* pCmdUI); afx_msg void OnProperties2(); afx_msg void OnUpdateProperties2(CCmdUI* pCmdUI); afx_msg void OnSetFocus(CWnd* pOldWnd); afx_msg void OnSettingChange(UINT uFlags, LPCTSTR lpszSection); DECLARE_MESSAGE_MAP() void InitPropList(); void SetPropListFont(); };
zzh-project-test
trunk/GoogleCodeTest/GoogleCodeTest/PropertiesWnd.h
C++
asf20
1,445
// GoogleCodeTestDoc.h : interface of the CGoogleCodeTestDoc class // #pragma once class CGoogleCodeTestDoc : public CDocument { protected: // create from serialization only CGoogleCodeTestDoc(); DECLARE_DYNCREATE(CGoogleCodeTestDoc) // Attributes public: // Operations public: // Overrides public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); #ifdef SHARED_HANDLERS virtual void InitializeSearchContent(); virtual void OnDrawThumbnail(CDC& dc, LPRECT lprcBounds); #endif // SHARED_HANDLERS // Implementation public: virtual ~CGoogleCodeTestDoc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: DECLARE_MESSAGE_MAP() #ifdef SHARED_HANDLERS // Helper function that sets search content for a Search Handler void SetSearchContent(const CString& value); #endif // SHARED_HANDLERS };
zzh-project-test
trunk/GoogleCodeTest/GoogleCodeTest/GoogleCodeTestDoc.h
C++
asf20
982
#pragma once #include "ViewTree.h" class CClassToolBar : public CMFCToolBar { virtual void OnUpdateCmdUI(CFrameWnd* /*pTarget*/, BOOL bDisableIfNoHndler) { CMFCToolBar::OnUpdateCmdUI((CFrameWnd*) GetOwner(), bDisableIfNoHndler); } virtual BOOL AllowShowOnList() const { return FALSE; } }; class CClassView : public CDockablePane { public: CClassView(); virtual ~CClassView(); void AdjustLayout(); void OnChangeVisualStyle(); protected: CClassToolBar m_wndToolBar; CViewTree m_wndClassView; CImageList m_ClassViewImages; UINT m_nCurrSort; void FillClassView(); // Overrides public: virtual BOOL PreTranslateMessage(MSG* pMsg); protected: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnContextMenu(CWnd* pWnd, CPoint point); afx_msg void OnClassAddMemberFunction(); afx_msg void OnClassAddMemberVariable(); afx_msg void OnClassDefinition(); afx_msg void OnClassProperties(); afx_msg void OnNewFolder(); afx_msg void OnPaint(); afx_msg void OnSetFocus(CWnd* pOldWnd); afx_msg LRESULT OnChangeActiveTab(WPARAM, LPARAM); afx_msg void OnSort(UINT id); afx_msg void OnUpdateSort(CCmdUI* pCmdUI); DECLARE_MESSAGE_MAP() };
zzh-project-test
trunk/GoogleCodeTest/GoogleCodeTest/ClassView.h
C++
asf20
1,280
#include "stdafx.h" #include "ViewTree.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CViewTree CViewTree::CViewTree() { } CViewTree::~CViewTree() { } BEGIN_MESSAGE_MAP(CViewTree, CTreeCtrl) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CViewTree message handlers BOOL CViewTree::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult) { BOOL bRes = CTreeCtrl::OnNotify(wParam, lParam, pResult); NMHDR* pNMHDR = (NMHDR*)lParam; ASSERT(pNMHDR != NULL); if (pNMHDR && pNMHDR->code == TTN_SHOW && GetToolTips() != NULL) { GetToolTips()->SetWindowPos(&wndTop, -1, -1, -1, -1, SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOSIZE); } return bRes; }
zzh-project-test
trunk/GoogleCodeTest/GoogleCodeTest/ViewTree.cpp
C++
asf20
880
// ChildFrm.cpp : implementation of the CChildFrame class // #include "stdafx.h" #include "GoogleCodeTest.h" #include "ChildFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CChildFrame IMPLEMENT_DYNCREATE(CChildFrame, CMDIChildWndEx) BEGIN_MESSAGE_MAP(CChildFrame, CMDIChildWndEx) END_MESSAGE_MAP() // CChildFrame construction/destruction CChildFrame::CChildFrame() { // TODO: add member initialization code here } CChildFrame::~CChildFrame() { } BOOL CChildFrame::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying the CREATESTRUCT cs if( !CMDIChildWndEx::PreCreateWindow(cs) ) return FALSE; return TRUE; } // CChildFrame diagnostics #ifdef _DEBUG void CChildFrame::AssertValid() const { CMDIChildWndEx::AssertValid(); } void CChildFrame::Dump(CDumpContext& dc) const { CMDIChildWndEx::Dump(dc); } #endif //_DEBUG // CChildFrame message handlers
zzh-project-test
trunk/GoogleCodeTest/GoogleCodeTest/ChildFrm.cpp
C++
asf20
978
#pragma once // Including SDKDDKVer.h defines the highest available Windows platform. // If you wish to build your application for a previous Windows platform, include WinSDKVer.h and // set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. #include <SDKDDKVer.h>
zzh-project-test
trunk/GoogleCodeTest/GoogleCodeTest/targetver.h
C
asf20
314
#pragma once ///////////////////////////////////////////////////////////////////////////// // COutputList window class COutputList : public CListBox { // Construction public: COutputList(); // Implementation public: virtual ~COutputList(); protected: afx_msg void OnContextMenu(CWnd* pWnd, CPoint point); afx_msg void OnEditCopy(); afx_msg void OnEditClear(); afx_msg void OnViewOutput(); DECLARE_MESSAGE_MAP() }; class COutputWnd : public CDockablePane { // Construction public: COutputWnd(); void UpdateFonts(); // Attributes protected: CMFCTabCtrl m_wndTabs; COutputList m_wndOutputBuild; COutputList m_wndOutputDebug; COutputList m_wndOutputFind; protected: void FillBuildWindow(); void FillDebugWindow(); void FillFindWindow(); void AdjustHorzScroll(CListBox& wndListBox); // Implementation public: virtual ~COutputWnd(); protected: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnSize(UINT nType, int cx, int cy); DECLARE_MESSAGE_MAP() };
zzh-project-test
trunk/GoogleCodeTest/GoogleCodeTest/OutputWnd.h
C++
asf20
1,061
// GoogleCodeTestDoc.cpp : implementation of the CGoogleCodeTestDoc class // #include "stdafx.h" // SHARED_HANDLERS can be defined in an ATL project implementing preview, thumbnail // and search filter handlers and allows sharing of document code with that project. #ifndef SHARED_HANDLERS #include "GoogleCodeTest.h" #endif #include "GoogleCodeTestDoc.h" #include <propkey.h> #ifdef _DEBUG #define new DEBUG_NEW #endif // CGoogleCodeTestDoc IMPLEMENT_DYNCREATE(CGoogleCodeTestDoc, CDocument) BEGIN_MESSAGE_MAP(CGoogleCodeTestDoc, CDocument) END_MESSAGE_MAP() // CGoogleCodeTestDoc construction/destruction CGoogleCodeTestDoc::CGoogleCodeTestDoc() { // TODO: add one-time construction code here } CGoogleCodeTestDoc::~CGoogleCodeTestDoc() { } BOOL CGoogleCodeTestDoc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; // TODO: add reinitialization code here // (SDI documents will reuse this document) return TRUE; } // CGoogleCodeTestDoc serialization void CGoogleCodeTestDoc::Serialize(CArchive& ar) { if (ar.IsStoring()) { // TODO: add storing code here } else { // TODO: add loading code here } } #ifdef SHARED_HANDLERS // Support for thumbnails void CGoogleCodeTestDoc::OnDrawThumbnail(CDC& dc, LPRECT lprcBounds) { // Modify this code to draw the document's data dc.FillSolidRect(lprcBounds, RGB(255, 255, 255)); CString strText = _T("TODO: implement thumbnail drawing here"); LOGFONT lf; CFont* pDefaultGUIFont = CFont::FromHandle((HFONT) GetStockObject(DEFAULT_GUI_FONT)); pDefaultGUIFont->GetLogFont(&lf); lf.lfHeight = 36; CFont fontDraw; fontDraw.CreateFontIndirect(&lf); CFont* pOldFont = dc.SelectObject(&fontDraw); dc.DrawText(strText, lprcBounds, DT_CENTER | DT_WORDBREAK); dc.SelectObject(pOldFont); } // Support for Search Handlers void CGoogleCodeTestDoc::InitializeSearchContent() { CString strSearchContent; // Set search contents from document's data. // The content parts should be separated by ";" // For example: strSearchContent = _T("point;rectangle;circle;ole object;"); SetSearchContent(strSearchContent); } void CGoogleCodeTestDoc::SetSearchContent(const CString& value) { if (value.IsEmpty()) { RemoveChunk(PKEY_Search_Contents.fmtid, PKEY_Search_Contents.pid); } else { CMFCFilterChunkValueImpl *pChunk = NULL; ATLTRY(pChunk = new CMFCFilterChunkValueImpl); if (pChunk != NULL) { pChunk->SetTextValue(PKEY_Search_Contents, value, CHUNK_TEXT); SetChunkValue(pChunk); } } } #endif // SHARED_HANDLERS // CGoogleCodeTestDoc diagnostics #ifdef _DEBUG void CGoogleCodeTestDoc::AssertValid() const { CDocument::AssertValid(); } void CGoogleCodeTestDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG // CGoogleCodeTestDoc commands
zzh-project-test
trunk/GoogleCodeTest/GoogleCodeTest/GoogleCodeTestDoc.cpp
C++
asf20
2,928
#include "stdafx.h" #include "PropertiesWnd.h" #include "Resource.h" #include "MainFrm.h" #include "GoogleCodeTest.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ///////////////////////////////////////////////////////////////////////////// // CResourceViewBar CPropertiesWnd::CPropertiesWnd() { } CPropertiesWnd::~CPropertiesWnd() { } BEGIN_MESSAGE_MAP(CPropertiesWnd, CDockablePane) ON_WM_CREATE() ON_WM_SIZE() ON_COMMAND(ID_EXPAND_ALL, OnExpandAllProperties) ON_UPDATE_COMMAND_UI(ID_EXPAND_ALL, OnUpdateExpandAllProperties) ON_COMMAND(ID_SORTPROPERTIES, OnSortProperties) ON_UPDATE_COMMAND_UI(ID_SORTPROPERTIES, OnUpdateSortProperties) ON_COMMAND(ID_PROPERTIES1, OnProperties1) ON_UPDATE_COMMAND_UI(ID_PROPERTIES1, OnUpdateProperties1) ON_COMMAND(ID_PROPERTIES2, OnProperties2) ON_UPDATE_COMMAND_UI(ID_PROPERTIES2, OnUpdateProperties2) ON_WM_SETFOCUS() ON_WM_SETTINGCHANGE() END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CResourceViewBar message handlers void CPropertiesWnd::AdjustLayout() { if (GetSafeHwnd() == NULL) { return; } CRect rectClient,rectCombo; GetClientRect(rectClient); m_wndObjectCombo.GetWindowRect(&rectCombo); int cyCmb = rectCombo.Size().cy; int cyTlb = m_wndToolBar.CalcFixedLayout(FALSE, TRUE).cy; m_wndObjectCombo.SetWindowPos(NULL, rectClient.left, rectClient.top, rectClient.Width(), 200, SWP_NOACTIVATE | SWP_NOZORDER); m_wndToolBar.SetWindowPos(NULL, rectClient.left, rectClient.top + cyCmb, rectClient.Width(), cyTlb, SWP_NOACTIVATE | SWP_NOZORDER); m_wndPropList.SetWindowPos(NULL, rectClient.left, rectClient.top + cyCmb + cyTlb, rectClient.Width(), rectClient.Height() -(cyCmb+cyTlb), SWP_NOACTIVATE | SWP_NOZORDER); } int CPropertiesWnd::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CDockablePane::OnCreate(lpCreateStruct) == -1) return -1; CRect rectDummy; rectDummy.SetRectEmpty(); // Create combo: const DWORD dwViewStyle = WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST | WS_BORDER | CBS_SORT | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; if (!m_wndObjectCombo.Create(dwViewStyle, rectDummy, this, 1)) { TRACE0("Failed to create Properties Combo \n"); return -1; // fail to create } m_wndObjectCombo.AddString(_T("Application")); m_wndObjectCombo.AddString(_T("Properties Window")); m_wndObjectCombo.SetCurSel(0); if (!m_wndPropList.Create(WS_VISIBLE | WS_CHILD, rectDummy, this, 2)) { TRACE0("Failed to create Properties Grid \n"); return -1; // fail to create } InitPropList(); m_wndToolBar.Create(this, AFX_DEFAULT_TOOLBAR_STYLE, IDR_PROPERTIES); m_wndToolBar.LoadToolBar(IDR_PROPERTIES, 0, 0, TRUE /* Is locked */); m_wndToolBar.CleanUpLockedImages(); m_wndToolBar.LoadBitmap(theApp.m_bHiColorIcons ? IDB_PROPERTIES_HC : IDR_PROPERTIES, 0, 0, TRUE /* Locked */); m_wndToolBar.SetPaneStyle(m_wndToolBar.GetPaneStyle() | CBRS_TOOLTIPS | CBRS_FLYBY); m_wndToolBar.SetPaneStyle(m_wndToolBar.GetPaneStyle() & ~(CBRS_GRIPPER | CBRS_SIZE_DYNAMIC | CBRS_BORDER_TOP | CBRS_BORDER_BOTTOM | CBRS_BORDER_LEFT | CBRS_BORDER_RIGHT)); m_wndToolBar.SetOwner(this); // All commands will be routed via this control , not via the parent frame: m_wndToolBar.SetRouteCommandsViaFrame(FALSE); AdjustLayout(); return 0; } void CPropertiesWnd::OnSize(UINT nType, int cx, int cy) { CDockablePane::OnSize(nType, cx, cy); AdjustLayout(); } void CPropertiesWnd::OnExpandAllProperties() { m_wndPropList.ExpandAll(); } void CPropertiesWnd::OnUpdateExpandAllProperties(CCmdUI* /* pCmdUI */) { } void CPropertiesWnd::OnSortProperties() { m_wndPropList.SetAlphabeticMode(!m_wndPropList.IsAlphabeticMode()); } void CPropertiesWnd::OnUpdateSortProperties(CCmdUI* pCmdUI) { pCmdUI->SetCheck(m_wndPropList.IsAlphabeticMode()); } void CPropertiesWnd::OnProperties1() { // TODO: Add your command handler code here } void CPropertiesWnd::OnUpdateProperties1(CCmdUI* /*pCmdUI*/) { // TODO: Add your command update UI handler code here } void CPropertiesWnd::OnProperties2() { // TODO: Add your command handler code here } void CPropertiesWnd::OnUpdateProperties2(CCmdUI* /*pCmdUI*/) { // TODO: Add your command update UI handler code here } void CPropertiesWnd::InitPropList() { SetPropListFont(); m_wndPropList.EnableHeaderCtrl(FALSE); m_wndPropList.EnableDescriptionArea(); m_wndPropList.SetVSDotNetLook(); m_wndPropList.MarkModifiedProperties(); CMFCPropertyGridProperty* pGroup1 = new CMFCPropertyGridProperty(_T("Appearance")); pGroup1->AddSubItem(new CMFCPropertyGridProperty(_T("3D Look"), (_variant_t) false, _T("Specifies the window's font will be non-bold and controls will have a 3D border"))); CMFCPropertyGridProperty* pProp = new CMFCPropertyGridProperty(_T("Border"), _T("Dialog Frame"), _T("One of: None, Thin, Resizable, or Dialog Frame")); pProp->AddOption(_T("None")); pProp->AddOption(_T("Thin")); pProp->AddOption(_T("Resizable")); pProp->AddOption(_T("Dialog Frame")); pProp->AllowEdit(FALSE); pGroup1->AddSubItem(pProp); pGroup1->AddSubItem(new CMFCPropertyGridProperty(_T("Caption"), (_variant_t) _T("About"), _T("Specifies the text that will be displayed in the window's title bar"))); m_wndPropList.AddProperty(pGroup1); CMFCPropertyGridProperty* pSize = new CMFCPropertyGridProperty(_T("Window Size"), 0, TRUE); pProp = new CMFCPropertyGridProperty(_T("Height"), (_variant_t) 250l, _T("Specifies the window's height")); pProp->EnableSpinControl(TRUE, 50, 300); pSize->AddSubItem(pProp); pProp = new CMFCPropertyGridProperty( _T("Width"), (_variant_t) 150l, _T("Specifies the window's width")); pProp->EnableSpinControl(TRUE, 50, 200); pSize->AddSubItem(pProp); m_wndPropList.AddProperty(pSize); CMFCPropertyGridProperty* pGroup2 = new CMFCPropertyGridProperty(_T("Font")); LOGFONT lf; CFont* font = CFont::FromHandle((HFONT) GetStockObject(DEFAULT_GUI_FONT)); font->GetLogFont(&lf); lstrcpy(lf.lfFaceName, _T("Arial")); pGroup2->AddSubItem(new CMFCPropertyGridFontProperty(_T("Font"), lf, CF_EFFECTS | CF_SCREENFONTS, _T("Specifies the default font for the window"))); pGroup2->AddSubItem(new CMFCPropertyGridProperty(_T("Use System Font"), (_variant_t) true, _T("Specifies that the window uses MS Shell Dlg font"))); m_wndPropList.AddProperty(pGroup2); CMFCPropertyGridProperty* pGroup3 = new CMFCPropertyGridProperty(_T("Misc")); pProp = new CMFCPropertyGridProperty(_T("(Name)"), _T("Application")); pProp->Enable(FALSE); pGroup3->AddSubItem(pProp); CMFCPropertyGridColorProperty* pColorProp = new CMFCPropertyGridColorProperty(_T("Window Color"), RGB(210, 192, 254), NULL, _T("Specifies the default window color")); pColorProp->EnableOtherButton(_T("Other...")); pColorProp->EnableAutomaticButton(_T("Default"), ::GetSysColor(COLOR_3DFACE)); pGroup3->AddSubItem(pColorProp); static const TCHAR szFilter[] = _T("Icon Files(*.ico)|*.ico|All Files(*.*)|*.*||"); pGroup3->AddSubItem(new CMFCPropertyGridFileProperty(_T("Icon"), TRUE, _T(""), _T("ico"), 0, szFilter, _T("Specifies the window icon"))); pGroup3->AddSubItem(new CMFCPropertyGridFileProperty(_T("Folder"), _T("c:\\"))); m_wndPropList.AddProperty(pGroup3); CMFCPropertyGridProperty* pGroup4 = new CMFCPropertyGridProperty(_T("Hierarchy")); CMFCPropertyGridProperty* pGroup41 = new CMFCPropertyGridProperty(_T("First sub-level")); pGroup4->AddSubItem(pGroup41); CMFCPropertyGridProperty* pGroup411 = new CMFCPropertyGridProperty(_T("Second sub-level")); pGroup41->AddSubItem(pGroup411); pGroup411->AddSubItem(new CMFCPropertyGridProperty(_T("Item 1"), (_variant_t) _T("Value 1"), _T("This is a description"))); pGroup411->AddSubItem(new CMFCPropertyGridProperty(_T("Item 2"), (_variant_t) _T("Value 2"), _T("This is a description"))); pGroup411->AddSubItem(new CMFCPropertyGridProperty(_T("Item 3"), (_variant_t) _T("Value 3"), _T("This is a description"))); pGroup4->Expand(FALSE); m_wndPropList.AddProperty(pGroup4); } void CPropertiesWnd::OnSetFocus(CWnd* pOldWnd) { CDockablePane::OnSetFocus(pOldWnd); m_wndPropList.SetFocus(); } void CPropertiesWnd::OnSettingChange(UINT uFlags, LPCTSTR lpszSection) { CDockablePane::OnSettingChange(uFlags, lpszSection); SetPropListFont(); } void CPropertiesWnd::SetPropListFont() { ::DeleteObject(m_fntPropList.Detach()); LOGFONT lf; afxGlobalData.fontRegular.GetLogFont(&lf); NONCLIENTMETRICS info; info.cbSize = sizeof(info); afxGlobalData.GetNonClientMetrics(info); lf.lfHeight = info.lfMenuFont.lfHeight; lf.lfWeight = info.lfMenuFont.lfWeight; lf.lfItalic = info.lfMenuFont.lfItalic; m_fntPropList.CreateFontIndirect(&lf); m_wndPropList.SetFont(&m_fntPropList); m_wndObjectCombo.SetFont(&m_fntPropList); }
zzh-project-test
trunk/GoogleCodeTest/GoogleCodeTest/PropertiesWnd.cpp
C++
asf20
9,017
// GoogleCodeTest.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "afxwinappex.h" #include "afxdialogex.h" #include "GoogleCodeTest.h" #include "MainFrm.h" #include "ChildFrm.h" #include "GoogleCodeTestDoc.h" #include "GoogleCodeTestView.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CGoogleCodeTestApp BEGIN_MESSAGE_MAP(CGoogleCodeTestApp, CWinAppEx) ON_COMMAND(ID_APP_ABOUT, &CGoogleCodeTestApp::OnAppAbout) // Standard file based document commands ON_COMMAND(ID_FILE_NEW, &CWinAppEx::OnFileNew) ON_COMMAND(ID_FILE_OPEN, &CWinAppEx::OnFileOpen) // Standard print setup command ON_COMMAND(ID_FILE_PRINT_SETUP, &CWinAppEx::OnFilePrintSetup) END_MESSAGE_MAP() // CGoogleCodeTestApp construction CGoogleCodeTestApp::CGoogleCodeTestApp() { m_bHiColorIcons = TRUE; // support Restart Manager m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_ALL_ASPECTS; #ifdef _MANAGED // If the application is built using Common Language Runtime support (/clr): // 1) This additional setting is needed for Restart Manager support to work properly. // 2) In your project, you must add a reference to System.Windows.Forms in order to build. System::Windows::Forms::Application::SetUnhandledExceptionMode(System::Windows::Forms::UnhandledExceptionMode::ThrowException); #endif // TODO: replace application ID string below with unique ID string; recommended // format for string is CompanyName.ProductName.SubProduct.VersionInformation SetAppID(_T("GoogleCodeTest.AppID.NoVersion")); // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CGoogleCodeTestApp object CGoogleCodeTestApp theApp; // CGoogleCodeTestApp initialization BOOL CGoogleCodeTestApp::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinAppEx::InitInstance(); // Initialize OLE libraries if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); EnableTaskbarInteraction(); // AfxInitRichEdit2() is required to use RichEdit control // AfxInitRichEdit2(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization SetRegistryKey(_T("Local AppWizard-Generated Applications")); LoadStdProfileSettings(4); // Load standard INI file options (including MRU) InitContextMenuManager(); InitKeyboardManager(); InitTooltipManager(); CMFCToolTipInfo ttParams; ttParams.m_bVislManagerTheme = TRUE; theApp.GetTooltipManager()->SetTooltipParams(AFX_TOOLTIP_TYPE_ALL, RUNTIME_CLASS(CMFCToolTipCtrl), &ttParams); // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views CMultiDocTemplate* pDocTemplate; pDocTemplate = new CMultiDocTemplate(IDR_GoogleCodeTestTYPE, RUNTIME_CLASS(CGoogleCodeTestDoc), RUNTIME_CLASS(CChildFrame), // custom MDI child frame RUNTIME_CLASS(CGoogleCodeTestView)); if (!pDocTemplate) return FALSE; AddDocTemplate(pDocTemplate); // create main MDI Frame window CMainFrame* pMainFrame = new CMainFrame; if (!pMainFrame || !pMainFrame->LoadFrame(IDR_MAINFRAME)) { delete pMainFrame; return FALSE; } m_pMainWnd = pMainFrame; // call DragAcceptFiles only if there's a suffix // In an MDI app, this should occur immediately after setting m_pMainWnd // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // Dispatch commands specified on the command line. Will return FALSE if // app was launched with /RegServer, /Register, /Unregserver or /Unregister. if (!ProcessShellCommand(cmdInfo)) return FALSE; // The main window has been initialized, so show and update it pMainFrame->ShowWindow(m_nCmdShow); pMainFrame->UpdateWindow(); return TRUE; } int CGoogleCodeTestApp::ExitInstance() { //TODO: handle additional resources you may have added AfxOleTerm(FALSE); return CWinAppEx::ExitInstance(); } // CGoogleCodeTestApp message handlers // CAboutDlg dialog used for App About class CAboutDlg : public CDialogEx { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // App command to run the dialog void CGoogleCodeTestApp::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } // CGoogleCodeTestApp customization load/save methods void CGoogleCodeTestApp::PreLoadState() { BOOL bNameValid; CString strName; bNameValid = strName.LoadString(IDS_EDIT_MENU); ASSERT(bNameValid); GetContextMenuManager()->AddMenu(strName, IDR_POPUP_EDIT); bNameValid = strName.LoadString(IDS_EXPLORER); ASSERT(bNameValid); GetContextMenuManager()->AddMenu(strName, IDR_POPUP_EXPLORER); } void CGoogleCodeTestApp::LoadCustomState() { } void CGoogleCodeTestApp::SaveCustomState() { } // CGoogleCodeTestApp message handlers
zzh-project-test
trunk/GoogleCodeTest/GoogleCodeTest/GoogleCodeTest.cpp
C++
asf20
6,156
#include "stdafx.h" #include "OutputWnd.h" #include "Resource.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // COutputBar COutputWnd::COutputWnd() { } COutputWnd::~COutputWnd() { } BEGIN_MESSAGE_MAP(COutputWnd, CDockablePane) ON_WM_CREATE() ON_WM_SIZE() END_MESSAGE_MAP() int COutputWnd::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CDockablePane::OnCreate(lpCreateStruct) == -1) return -1; CRect rectDummy; rectDummy.SetRectEmpty(); // Create tabs window: if (!m_wndTabs.Create(CMFCTabCtrl::STYLE_FLAT, rectDummy, this, 1)) { TRACE0("Failed to create output tab window\n"); return -1; // fail to create } // Create output panes: const DWORD dwStyle = LBS_NOINTEGRALHEIGHT | WS_CHILD | WS_VISIBLE | WS_HSCROLL | WS_VSCROLL; if (!m_wndOutputBuild.Create(dwStyle, rectDummy, &m_wndTabs, 2) || !m_wndOutputDebug.Create(dwStyle, rectDummy, &m_wndTabs, 3) || !m_wndOutputFind.Create(dwStyle, rectDummy, &m_wndTabs, 4)) { TRACE0("Failed to create output windows\n"); return -1; // fail to create } UpdateFonts(); CString strTabName; BOOL bNameValid; // Attach list windows to tab: bNameValid = strTabName.LoadString(IDS_BUILD_TAB); ASSERT(bNameValid); m_wndTabs.AddTab(&m_wndOutputBuild, strTabName, (UINT)0); bNameValid = strTabName.LoadString(IDS_DEBUG_TAB); ASSERT(bNameValid); m_wndTabs.AddTab(&m_wndOutputDebug, strTabName, (UINT)1); bNameValid = strTabName.LoadString(IDS_FIND_TAB); ASSERT(bNameValid); m_wndTabs.AddTab(&m_wndOutputFind, strTabName, (UINT)2); // Fill output tabs with some dummy text (nothing magic here) FillBuildWindow(); FillDebugWindow(); FillFindWindow(); return 0; } void COutputWnd::OnSize(UINT nType, int cx, int cy) { CDockablePane::OnSize(nType, cx, cy); // Tab control should cover the whole client area: m_wndTabs.SetWindowPos (NULL, -1, -1, cx, cy, SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER); } void COutputWnd::AdjustHorzScroll(CListBox& wndListBox) { CClientDC dc(this); CFont* pOldFont = dc.SelectObject(&afxGlobalData.fontRegular); int cxExtentMax = 0; for (int i = 0; i < wndListBox.GetCount(); i ++) { CString strItem; wndListBox.GetText(i, strItem); cxExtentMax = max(cxExtentMax, dc.GetTextExtent(strItem).cx); } wndListBox.SetHorizontalExtent(cxExtentMax); dc.SelectObject(pOldFont); } void COutputWnd::FillBuildWindow() { m_wndOutputBuild.AddString(_T("Build output is being displayed here.")); m_wndOutputBuild.AddString(_T("The output is being displayed in rows of a list view")); m_wndOutputBuild.AddString(_T("but you can change the way it is displayed as you wish...")); } void COutputWnd::FillDebugWindow() { m_wndOutputDebug.AddString(_T("Debug output is being displayed here.")); m_wndOutputDebug.AddString(_T("The output is being displayed in rows of a list view")); m_wndOutputDebug.AddString(_T("but you can change the way it is displayed as you wish...")); } void COutputWnd::FillFindWindow() { m_wndOutputFind.AddString(_T("Find output is being displayed here.")); m_wndOutputFind.AddString(_T("The output is being displayed in rows of a list view")); m_wndOutputFind.AddString(_T("but you can change the way it is displayed as you wish...")); } void COutputWnd::UpdateFonts() { m_wndOutputBuild.SetFont(&afxGlobalData.fontRegular); m_wndOutputDebug.SetFont(&afxGlobalData.fontRegular); m_wndOutputFind.SetFont(&afxGlobalData.fontRegular); } ///////////////////////////////////////////////////////////////////////////// // COutputList1 COutputList::COutputList() { } COutputList::~COutputList() { } BEGIN_MESSAGE_MAP(COutputList, CListBox) ON_WM_CONTEXTMENU() ON_COMMAND(ID_EDIT_COPY, OnEditCopy) ON_COMMAND(ID_EDIT_CLEAR, OnEditClear) ON_COMMAND(ID_VIEW_OUTPUTWND, OnViewOutput) ON_WM_WINDOWPOSCHANGING() END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // COutputList message handlers void COutputList::OnContextMenu(CWnd* /*pWnd*/, CPoint point) { CMenu menu; menu.LoadMenu(IDR_OUTPUT_POPUP); CMenu* pSumMenu = menu.GetSubMenu(0); if (AfxGetMainWnd()->IsKindOf(RUNTIME_CLASS(CMDIFrameWndEx))) { CMFCPopupMenu* pPopupMenu = new CMFCPopupMenu; if (!pPopupMenu->Create(this, point.x, point.y, (HMENU)pSumMenu->m_hMenu, FALSE, TRUE)) return; ((CMDIFrameWndEx*)AfxGetMainWnd())->OnShowPopupMenu(pPopupMenu); UpdateDialogControls(this, FALSE); } SetFocus(); } void COutputList::OnEditCopy() { MessageBox(_T("Copy output")); } void COutputList::OnEditClear() { MessageBox(_T("Clear output")); } void COutputList::OnViewOutput() { CDockablePane* pParentBar = DYNAMIC_DOWNCAST(CDockablePane, GetOwner()); CMDIFrameWndEx* pMainFrame = DYNAMIC_DOWNCAST(CMDIFrameWndEx, GetTopLevelFrame()); if (pMainFrame != NULL && pParentBar != NULL) { pMainFrame->SetFocus(); pMainFrame->ShowPane(pParentBar, FALSE, FALSE, FALSE); pMainFrame->RecalcLayout(); } }
zzh-project-test
trunk/GoogleCodeTest/GoogleCodeTest/OutputWnd.cpp
C++
asf20
5,258
#include "stdafx.h" #include "MainFrm.h" #include "ClassView.h" #include "Resource.h" #include "GoogleCodeTest.h" class CClassViewMenuButton : public CMFCToolBarMenuButton { friend class CClassView; DECLARE_SERIAL(CClassViewMenuButton) public: CClassViewMenuButton(HMENU hMenu = NULL) : CMFCToolBarMenuButton((UINT)-1, hMenu, -1) { } virtual void OnDraw(CDC* pDC, const CRect& rect, CMFCToolBarImages* pImages, BOOL bHorz = TRUE, BOOL bCustomizeMode = FALSE, BOOL bHighlight = FALSE, BOOL bDrawBorder = TRUE, BOOL bGrayDisabledButtons = TRUE) { pImages = CMFCToolBar::GetImages(); CAfxDrawState ds; pImages->PrepareDrawImage(ds); CMFCToolBarMenuButton::OnDraw(pDC, rect, pImages, bHorz, bCustomizeMode, bHighlight, bDrawBorder, bGrayDisabledButtons); pImages->EndDrawImage(ds); } }; IMPLEMENT_SERIAL(CClassViewMenuButton, CMFCToolBarMenuButton, 1) ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CClassView::CClassView() { m_nCurrSort = ID_SORTING_GROUPBYTYPE; } CClassView::~CClassView() { } BEGIN_MESSAGE_MAP(CClassView, CDockablePane) ON_WM_CREATE() ON_WM_SIZE() ON_WM_CONTEXTMENU() ON_COMMAND(ID_CLASS_ADD_MEMBER_FUNCTION, OnClassAddMemberFunction) ON_COMMAND(ID_CLASS_ADD_MEMBER_VARIABLE, OnClassAddMemberVariable) ON_COMMAND(ID_CLASS_DEFINITION, OnClassDefinition) ON_COMMAND(ID_CLASS_PROPERTIES, OnClassProperties) ON_COMMAND(ID_NEW_FOLDER, OnNewFolder) ON_WM_PAINT() ON_WM_SETFOCUS() ON_COMMAND_RANGE(ID_SORTING_GROUPBYTYPE, ID_SORTING_SORTBYACCESS, OnSort) ON_UPDATE_COMMAND_UI_RANGE(ID_SORTING_GROUPBYTYPE, ID_SORTING_SORTBYACCESS, OnUpdateSort) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CClassView message handlers int CClassView::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CDockablePane::OnCreate(lpCreateStruct) == -1) return -1; CRect rectDummy; rectDummy.SetRectEmpty(); // Create views: const DWORD dwViewStyle = WS_CHILD | WS_VISIBLE | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; if (!m_wndClassView.Create(dwViewStyle, rectDummy, this, 2)) { TRACE0("Failed to create Class View\n"); return -1; // fail to create } // Load images: m_wndToolBar.Create(this, AFX_DEFAULT_TOOLBAR_STYLE, IDR_SORT); m_wndToolBar.LoadToolBar(IDR_SORT, 0, 0, TRUE /* Is locked */); OnChangeVisualStyle(); m_wndToolBar.SetPaneStyle(m_wndToolBar.GetPaneStyle() | CBRS_TOOLTIPS | CBRS_FLYBY); m_wndToolBar.SetPaneStyle(m_wndToolBar.GetPaneStyle() & ~(CBRS_GRIPPER | CBRS_SIZE_DYNAMIC | CBRS_BORDER_TOP | CBRS_BORDER_BOTTOM | CBRS_BORDER_LEFT | CBRS_BORDER_RIGHT)); m_wndToolBar.SetOwner(this); // All commands will be routed via this control , not via the parent frame: m_wndToolBar.SetRouteCommandsViaFrame(FALSE); CMenu menuSort; menuSort.LoadMenu(IDR_POPUP_SORT); m_wndToolBar.ReplaceButton(ID_SORT_MENU, CClassViewMenuButton(menuSort.GetSubMenu(0)->GetSafeHmenu())); CClassViewMenuButton* pButton = DYNAMIC_DOWNCAST(CClassViewMenuButton, m_wndToolBar.GetButton(0)); if (pButton != NULL) { pButton->m_bText = FALSE; pButton->m_bImage = TRUE; pButton->SetImage(GetCmdMgr()->GetCmdImage(m_nCurrSort)); pButton->SetMessageWnd(this); } // Fill in some static tree view data (dummy code, nothing magic here) FillClassView(); return 0; } void CClassView::OnSize(UINT nType, int cx, int cy) { CDockablePane::OnSize(nType, cx, cy); AdjustLayout(); } void CClassView::FillClassView() { HTREEITEM hRoot = m_wndClassView.InsertItem(_T("FakeApp classes"), 0, 0); m_wndClassView.SetItemState(hRoot, TVIS_BOLD, TVIS_BOLD); HTREEITEM hClass = m_wndClassView.InsertItem(_T("CFakeAboutDlg"), 1, 1, hRoot); m_wndClassView.InsertItem(_T("CFakeAboutDlg()"), 3, 3, hClass); m_wndClassView.Expand(hRoot, TVE_EXPAND); hClass = m_wndClassView.InsertItem(_T("CFakeApp"), 1, 1, hRoot); m_wndClassView.InsertItem(_T("CFakeApp()"), 3, 3, hClass); m_wndClassView.InsertItem(_T("InitInstance()"), 3, 3, hClass); m_wndClassView.InsertItem(_T("OnAppAbout()"), 3, 3, hClass); hClass = m_wndClassView.InsertItem(_T("CFakeAppDoc"), 1, 1, hRoot); m_wndClassView.InsertItem(_T("CFakeAppDoc()"), 4, 4, hClass); m_wndClassView.InsertItem(_T("~CFakeAppDoc()"), 3, 3, hClass); m_wndClassView.InsertItem(_T("OnNewDocument()"), 3, 3, hClass); hClass = m_wndClassView.InsertItem(_T("CFakeAppView"), 1, 1, hRoot); m_wndClassView.InsertItem(_T("CFakeAppView()"), 4, 4, hClass); m_wndClassView.InsertItem(_T("~CFakeAppView()"), 3, 3, hClass); m_wndClassView.InsertItem(_T("GetDocument()"), 3, 3, hClass); m_wndClassView.Expand(hClass, TVE_EXPAND); hClass = m_wndClassView.InsertItem(_T("CFakeAppFrame"), 1, 1, hRoot); m_wndClassView.InsertItem(_T("CFakeAppFrame()"), 3, 3, hClass); m_wndClassView.InsertItem(_T("~CFakeAppFrame()"), 3, 3, hClass); m_wndClassView.InsertItem(_T("m_wndMenuBar"), 6, 6, hClass); m_wndClassView.InsertItem(_T("m_wndToolBar"), 6, 6, hClass); m_wndClassView.InsertItem(_T("m_wndStatusBar"), 6, 6, hClass); hClass = m_wndClassView.InsertItem(_T("Globals"), 2, 2, hRoot); m_wndClassView.InsertItem(_T("theFakeApp"), 5, 5, hClass); m_wndClassView.Expand(hClass, TVE_EXPAND); } void CClassView::OnContextMenu(CWnd* pWnd, CPoint point) { CTreeCtrl* pWndTree = (CTreeCtrl*)&m_wndClassView; ASSERT_VALID(pWndTree); if (pWnd != pWndTree) { CDockablePane::OnContextMenu(pWnd, point); return; } if (point != CPoint(-1, -1)) { // Select clicked item: CPoint ptTree = point; pWndTree->ScreenToClient(&ptTree); UINT flags = 0; HTREEITEM hTreeItem = pWndTree->HitTest(ptTree, &flags); if (hTreeItem != NULL) { pWndTree->SelectItem(hTreeItem); } } pWndTree->SetFocus(); CMenu menu; menu.LoadMenu(IDR_POPUP_SORT); CMenu* pSumMenu = menu.GetSubMenu(0); if (AfxGetMainWnd()->IsKindOf(RUNTIME_CLASS(CMDIFrameWndEx))) { CMFCPopupMenu* pPopupMenu = new CMFCPopupMenu; if (!pPopupMenu->Create(this, point.x, point.y, (HMENU)pSumMenu->m_hMenu, FALSE, TRUE)) return; ((CMDIFrameWndEx*)AfxGetMainWnd())->OnShowPopupMenu(pPopupMenu); UpdateDialogControls(this, FALSE); } } void CClassView::AdjustLayout() { if (GetSafeHwnd() == NULL) { return; } CRect rectClient; GetClientRect(rectClient); int cyTlb = m_wndToolBar.CalcFixedLayout(FALSE, TRUE).cy; m_wndToolBar.SetWindowPos(NULL, rectClient.left, rectClient.top, rectClient.Width(), cyTlb, SWP_NOACTIVATE | SWP_NOZORDER); m_wndClassView.SetWindowPos(NULL, rectClient.left + 1, rectClient.top + cyTlb + 1, rectClient.Width() - 2, rectClient.Height() - cyTlb - 2, SWP_NOACTIVATE | SWP_NOZORDER); } BOOL CClassView::PreTranslateMessage(MSG* pMsg) { return CDockablePane::PreTranslateMessage(pMsg); } void CClassView::OnSort(UINT id) { if (m_nCurrSort == id) { return; } m_nCurrSort = id; CClassViewMenuButton* pButton = DYNAMIC_DOWNCAST(CClassViewMenuButton, m_wndToolBar.GetButton(0)); if (pButton != NULL) { pButton->SetImage(GetCmdMgr()->GetCmdImage(id)); m_wndToolBar.Invalidate(); m_wndToolBar.UpdateWindow(); } } void CClassView::OnUpdateSort(CCmdUI* pCmdUI) { pCmdUI->SetCheck(pCmdUI->m_nID == m_nCurrSort); } void CClassView::OnClassAddMemberFunction() { AfxMessageBox(_T("Add member function...")); } void CClassView::OnClassAddMemberVariable() { // TODO: Add your command handler code here } void CClassView::OnClassDefinition() { // TODO: Add your command handler code here } void CClassView::OnClassProperties() { // TODO: Add your command handler code here } void CClassView::OnNewFolder() { AfxMessageBox(_T("New Folder...")); } void CClassView::OnPaint() { CPaintDC dc(this); // device context for painting CRect rectTree; m_wndClassView.GetWindowRect(rectTree); ScreenToClient(rectTree); rectTree.InflateRect(1, 1); dc.Draw3dRect(rectTree, ::GetSysColor(COLOR_3DSHADOW), ::GetSysColor(COLOR_3DSHADOW)); } void CClassView::OnSetFocus(CWnd* pOldWnd) { CDockablePane::OnSetFocus(pOldWnd); m_wndClassView.SetFocus(); } void CClassView::OnChangeVisualStyle() { m_ClassViewImages.DeleteImageList(); UINT uiBmpId = theApp.m_bHiColorIcons ? IDB_CLASS_VIEW_24 : IDB_CLASS_VIEW; CBitmap bmp; if (!bmp.LoadBitmap(uiBmpId)) { TRACE(_T("Can't load bitmap: %x\n"), uiBmpId); ASSERT(FALSE); return; } BITMAP bmpObj; bmp.GetBitmap(&bmpObj); UINT nFlags = ILC_MASK; nFlags |= (theApp.m_bHiColorIcons) ? ILC_COLOR24 : ILC_COLOR4; m_ClassViewImages.Create(16, bmpObj.bmHeight, nFlags, 0, 0); m_ClassViewImages.Add(&bmp, RGB(255, 0, 0)); m_wndClassView.SetImageList(&m_ClassViewImages, TVSIL_NORMAL); m_wndToolBar.CleanUpLockedImages(); m_wndToolBar.LoadBitmap(theApp.m_bHiColorIcons ? IDB_SORT_24 : IDR_SORT, 0, 0, TRUE /* Locked */); }
zzh-project-test
trunk/GoogleCodeTest/GoogleCodeTest/ClassView.cpp
C++
asf20
9,171
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, // but are changed infrequently #pragma once #ifndef _SECURE_ATL #define _SECURE_ATL 1 #endif #ifndef VC_EXTRALEAN #define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers #endif #include "targetver.h" #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit // turns off MFC's hiding of some common and often safely ignored warning messages #define _AFX_ALL_WARNINGS #include <afxwin.h> // MFC core and standard components #include <afxext.h> // MFC extensions #include <afxdisp.h> // MFC Automation classes #ifndef _AFX_NO_OLE_SUPPORT #include <afxdtctl.h> // MFC support for Internet Explorer 4 Common Controls #endif #ifndef _AFX_NO_AFXCMN_SUPPORT #include <afxcmn.h> // MFC support for Windows Common Controls #endif // _AFX_NO_AFXCMN_SUPPORT #include <afxcontrolbars.h> // MFC support for ribbons and control bars #ifdef _UNICODE #if defined _M_IX86 #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"") #elif defined _M_X64 #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"") #else #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") #endif #endif
zzh-project-test
trunk/GoogleCodeTest/GoogleCodeTest/stdafx.h
C
asf20
1,807
// MainFrm.h : interface of the CMainFrame class // #pragma once #include "FileView.h" #include "ClassView.h" #include "OutputWnd.h" #include "PropertiesWnd.h" class CMainFrame : public CMDIFrameWndEx { DECLARE_DYNAMIC(CMainFrame) public: CMainFrame(); // Attributes public: // Operations public: // Overrides public: virtual BOOL PreCreateWindow(CREATESTRUCT& cs); virtual BOOL LoadFrame(UINT nIDResource, DWORD dwDefaultStyle = WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, CWnd* pParentWnd = NULL, CCreateContext* pContext = NULL); // Implementation public: virtual ~CMainFrame(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // control bar embedded members CMFCMenuBar m_wndMenuBar; CMFCToolBar m_wndToolBar; CMFCStatusBar m_wndStatusBar; CMFCToolBarImages m_UserImages; CFileView m_wndFileView; CClassView m_wndClassView; COutputWnd m_wndOutput; CPropertiesWnd m_wndProperties; // Generated message map functions protected: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnWindowManager(); afx_msg void OnViewCustomize(); afx_msg LRESULT OnToolbarCreateNew(WPARAM wp, LPARAM lp); afx_msg void OnApplicationLook(UINT id); afx_msg void OnUpdateApplicationLook(CCmdUI* pCmdUI); afx_msg void OnSettingChange(UINT uFlags, LPCTSTR lpszSection); DECLARE_MESSAGE_MAP() BOOL CreateDockingWindows(); void SetDockingWindowIcons(BOOL bHiColorIcons); };
zzh-project-test
trunk/GoogleCodeTest/GoogleCodeTest/MainFrm.h
C++
asf20
1,561
// MainFrm.cpp : implementation of the CMainFrame class // #include "stdafx.h" #include "GoogleCodeTest.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CMainFrame IMPLEMENT_DYNAMIC(CMainFrame, CMDIFrameWndEx) const int iMaxUserToolbars = 10; const UINT uiFirstUserToolBarId = AFX_IDW_CONTROLBAR_FIRST + 40; const UINT uiLastUserToolBarId = uiFirstUserToolBarId + iMaxUserToolbars - 1; BEGIN_MESSAGE_MAP(CMainFrame, CMDIFrameWndEx) ON_WM_CREATE() ON_COMMAND(ID_WINDOW_MANAGER, &CMainFrame::OnWindowManager) ON_COMMAND(ID_VIEW_CUSTOMIZE, &CMainFrame::OnViewCustomize) ON_REGISTERED_MESSAGE(AFX_WM_CREATETOOLBAR, &CMainFrame::OnToolbarCreateNew) ON_COMMAND_RANGE(ID_VIEW_APPLOOK_WIN_2000, ID_VIEW_APPLOOK_WINDOWS_7, &CMainFrame::OnApplicationLook) ON_UPDATE_COMMAND_UI_RANGE(ID_VIEW_APPLOOK_WIN_2000, ID_VIEW_APPLOOK_WINDOWS_7, &CMainFrame::OnUpdateApplicationLook) ON_WM_SETTINGCHANGE() END_MESSAGE_MAP() static UINT indicators[] = { ID_SEPARATOR, // status line indicator ID_INDICATOR_CAPS, ID_INDICATOR_NUM, ID_INDICATOR_SCRL, }; // CMainFrame construction/destruction CMainFrame::CMainFrame() { // TODO: add member initialization code here theApp.m_nAppLook = theApp.GetInt(_T("ApplicationLook"), ID_VIEW_APPLOOK_VS_2008); } CMainFrame::~CMainFrame() { } int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CMDIFrameWndEx::OnCreate(lpCreateStruct) == -1) return -1; BOOL bNameValid; // set the visual manager and style based on persisted value OnApplicationLook(theApp.m_nAppLook); CMDITabInfo mdiTabParams; mdiTabParams.m_style = CMFCTabCtrl::STYLE_3D_ONENOTE; // other styles available... mdiTabParams.m_bActiveTabCloseButton = TRUE; // set to FALSE to place close button at right of tab area mdiTabParams.m_bTabIcons = FALSE; // set to TRUE to enable document icons on MDI taba mdiTabParams.m_bAutoColor = TRUE; // set to FALSE to disable auto-coloring of MDI tabs mdiTabParams.m_bDocumentMenu = TRUE; // enable the document menu at the right edge of the tab area EnableMDITabbedGroups(TRUE, mdiTabParams); if (!m_wndMenuBar.Create(this)) { TRACE0("Failed to create menubar\n"); return -1; // fail to create } m_wndMenuBar.SetPaneStyle(m_wndMenuBar.GetPaneStyle() | CBRS_SIZE_DYNAMIC | CBRS_TOOLTIPS | CBRS_FLYBY); // prevent the menu bar from taking the focus on activation CMFCPopupMenu::SetForceMenuFocus(FALSE); if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) || !m_wndToolBar.LoadToolBar(theApp.m_bHiColorIcons ? IDR_MAINFRAME_256 : IDR_MAINFRAME)) { TRACE0("Failed to create toolbar\n"); return -1; // fail to create } CString strToolBarName; bNameValid = strToolBarName.LoadString(IDS_TOOLBAR_STANDARD); ASSERT(bNameValid); m_wndToolBar.SetWindowText(strToolBarName); CString strCustomize; bNameValid = strCustomize.LoadString(IDS_TOOLBAR_CUSTOMIZE); ASSERT(bNameValid); m_wndToolBar.EnableCustomizeButton(TRUE, ID_VIEW_CUSTOMIZE, strCustomize); // Allow user-defined toolbars operations: InitUserToolbars(NULL, uiFirstUserToolBarId, uiLastUserToolBarId); if (!m_wndStatusBar.Create(this)) { TRACE0("Failed to create status bar\n"); return -1; // fail to create } m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT)); // TODO: Delete these five lines if you don't want the toolbar and menubar to be dockable m_wndMenuBar.EnableDocking(CBRS_ALIGN_ANY); m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY); EnableDocking(CBRS_ALIGN_ANY); DockPane(&m_wndMenuBar); DockPane(&m_wndToolBar); // enable Visual Studio 2005 style docking window behavior CDockingManager::SetDockingMode(DT_SMART); // enable Visual Studio 2005 style docking window auto-hide behavior EnableAutoHidePanes(CBRS_ALIGN_ANY); // Load menu item image (not placed on any standard toolbars): CMFCToolBar::AddToolBarForImageCollection(IDR_MENU_IMAGES, theApp.m_bHiColorIcons ? IDB_MENU_IMAGES_24 : 0); // create docking windows if (!CreateDockingWindows()) { TRACE0("Failed to create docking windows\n"); return -1; } m_wndFileView.EnableDocking(CBRS_ALIGN_ANY); m_wndClassView.EnableDocking(CBRS_ALIGN_ANY); DockPane(&m_wndFileView); CDockablePane* pTabbedBar = NULL; m_wndClassView.AttachToTabWnd(&m_wndFileView, DM_SHOW, TRUE, &pTabbedBar); m_wndOutput.EnableDocking(CBRS_ALIGN_ANY); DockPane(&m_wndOutput); m_wndProperties.EnableDocking(CBRS_ALIGN_ANY); DockPane(&m_wndProperties); // Enable enhanced windows management dialog EnableWindowsDialog(ID_WINDOW_MANAGER, ID_WINDOW_MANAGER, TRUE); // Enable toolbar and docking window menu replacement EnablePaneMenu(TRUE, ID_VIEW_CUSTOMIZE, strCustomize, ID_VIEW_TOOLBAR); // enable quick (Alt+drag) toolbar customization CMFCToolBar::EnableQuickCustomization(); if (CMFCToolBar::GetUserImages() == NULL) { // load user-defined toolbar images if (m_UserImages.Load(_T(".\\UserImages.bmp"))) { CMFCToolBar::SetUserImages(&m_UserImages); } } // enable menu personalization (most-recently used commands) // TODO: define your own basic commands, ensuring that each pulldown menu has at least one basic command. CList<UINT, UINT> lstBasicCommands; lstBasicCommands.AddTail(ID_FILE_NEW); lstBasicCommands.AddTail(ID_FILE_OPEN); lstBasicCommands.AddTail(ID_FILE_SAVE); lstBasicCommands.AddTail(ID_FILE_PRINT); lstBasicCommands.AddTail(ID_APP_EXIT); lstBasicCommands.AddTail(ID_EDIT_CUT); lstBasicCommands.AddTail(ID_EDIT_PASTE); lstBasicCommands.AddTail(ID_EDIT_UNDO); lstBasicCommands.AddTail(ID_APP_ABOUT); lstBasicCommands.AddTail(ID_VIEW_STATUS_BAR); lstBasicCommands.AddTail(ID_VIEW_TOOLBAR); lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2003); lstBasicCommands.AddTail(ID_VIEW_APPLOOK_VS_2005); lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2007_BLUE); lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2007_SILVER); lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2007_BLACK); lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2007_AQUA); lstBasicCommands.AddTail(ID_VIEW_APPLOOK_WINDOWS_7); lstBasicCommands.AddTail(ID_SORTING_SORTALPHABETIC); lstBasicCommands.AddTail(ID_SORTING_SORTBYTYPE); lstBasicCommands.AddTail(ID_SORTING_SORTBYACCESS); lstBasicCommands.AddTail(ID_SORTING_GROUPBYTYPE); CMFCToolBar::SetBasicCommands(lstBasicCommands); // Switch the order of document name and application name on the window title bar. This // improves the usability of the taskbar because the document name is visible with the thumbnail. ModifyStyle(0, FWS_PREFIXTITLE); return 0; } BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if( !CMDIFrameWndEx::PreCreateWindow(cs) ) return FALSE; // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return TRUE; } BOOL CMainFrame::CreateDockingWindows() { BOOL bNameValid; // Create class view CString strClassView; bNameValid = strClassView.LoadString(IDS_CLASS_VIEW); ASSERT(bNameValid); if (!m_wndClassView.Create(strClassView, this, CRect(0, 0, 200, 200), TRUE, ID_VIEW_CLASSVIEW, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_LEFT | CBRS_FLOAT_MULTI)) { TRACE0("Failed to create Class View window\n"); return FALSE; // failed to create } // Create file view CString strFileView; bNameValid = strFileView.LoadString(IDS_FILE_VIEW); ASSERT(bNameValid); if (!m_wndFileView.Create(strFileView, this, CRect(0, 0, 200, 200), TRUE, ID_VIEW_FILEVIEW, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_LEFT| CBRS_FLOAT_MULTI)) { TRACE0("Failed to create File View window\n"); return FALSE; // failed to create } // Create output window CString strOutputWnd; bNameValid = strOutputWnd.LoadString(IDS_OUTPUT_WND); ASSERT(bNameValid); if (!m_wndOutput.Create(strOutputWnd, this, CRect(0, 0, 100, 100), TRUE, ID_VIEW_OUTPUTWND, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_BOTTOM | CBRS_FLOAT_MULTI)) { TRACE0("Failed to create Output window\n"); return FALSE; // failed to create } // Create properties window CString strPropertiesWnd; bNameValid = strPropertiesWnd.LoadString(IDS_PROPERTIES_WND); ASSERT(bNameValid); if (!m_wndProperties.Create(strPropertiesWnd, this, CRect(0, 0, 200, 200), TRUE, ID_VIEW_PROPERTIESWND, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_RIGHT | CBRS_FLOAT_MULTI)) { TRACE0("Failed to create Properties window\n"); return FALSE; // failed to create } SetDockingWindowIcons(theApp.m_bHiColorIcons); return TRUE; } void CMainFrame::SetDockingWindowIcons(BOOL bHiColorIcons) { HICON hFileViewIcon = (HICON) ::LoadImage(::AfxGetResourceHandle(), MAKEINTRESOURCE(bHiColorIcons ? IDI_FILE_VIEW_HC : IDI_FILE_VIEW), IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), 0); m_wndFileView.SetIcon(hFileViewIcon, FALSE); HICON hClassViewIcon = (HICON) ::LoadImage(::AfxGetResourceHandle(), MAKEINTRESOURCE(bHiColorIcons ? IDI_CLASS_VIEW_HC : IDI_CLASS_VIEW), IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), 0); m_wndClassView.SetIcon(hClassViewIcon, FALSE); HICON hOutputBarIcon = (HICON) ::LoadImage(::AfxGetResourceHandle(), MAKEINTRESOURCE(bHiColorIcons ? IDI_OUTPUT_WND_HC : IDI_OUTPUT_WND), IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), 0); m_wndOutput.SetIcon(hOutputBarIcon, FALSE); HICON hPropertiesBarIcon = (HICON) ::LoadImage(::AfxGetResourceHandle(), MAKEINTRESOURCE(bHiColorIcons ? IDI_PROPERTIES_WND_HC : IDI_PROPERTIES_WND), IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), 0); m_wndProperties.SetIcon(hPropertiesBarIcon, FALSE); UpdateMDITabbedBarsIcons(); } // CMainFrame diagnostics #ifdef _DEBUG void CMainFrame::AssertValid() const { CMDIFrameWndEx::AssertValid(); } void CMainFrame::Dump(CDumpContext& dc) const { CMDIFrameWndEx::Dump(dc); } #endif //_DEBUG // CMainFrame message handlers void CMainFrame::OnWindowManager() { ShowWindowsDialog(); } void CMainFrame::OnViewCustomize() { CMFCToolBarsCustomizeDialog* pDlgCust = new CMFCToolBarsCustomizeDialog(this, TRUE /* scan menus */); pDlgCust->EnableUserDefinedToolbars(); pDlgCust->Create(); } LRESULT CMainFrame::OnToolbarCreateNew(WPARAM wp,LPARAM lp) { LRESULT lres = CMDIFrameWndEx::OnToolbarCreateNew(wp,lp); if (lres == 0) { return 0; } CMFCToolBar* pUserToolbar = (CMFCToolBar*)lres; ASSERT_VALID(pUserToolbar); BOOL bNameValid; CString strCustomize; bNameValid = strCustomize.LoadString(IDS_TOOLBAR_CUSTOMIZE); ASSERT(bNameValid); pUserToolbar->EnableCustomizeButton(TRUE, ID_VIEW_CUSTOMIZE, strCustomize); return lres; } void CMainFrame::OnApplicationLook(UINT id) { CWaitCursor wait; theApp.m_nAppLook = id; switch (theApp.m_nAppLook) { case ID_VIEW_APPLOOK_WIN_2000: CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManager)); break; case ID_VIEW_APPLOOK_OFF_XP: CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOfficeXP)); break; case ID_VIEW_APPLOOK_WIN_XP: CMFCVisualManagerWindows::m_b3DTabsXPTheme = TRUE; CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows)); break; case ID_VIEW_APPLOOK_OFF_2003: CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOffice2003)); CDockingManager::SetDockingMode(DT_SMART); break; case ID_VIEW_APPLOOK_VS_2005: CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerVS2005)); CDockingManager::SetDockingMode(DT_SMART); break; case ID_VIEW_APPLOOK_VS_2008: CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerVS2008)); CDockingManager::SetDockingMode(DT_SMART); break; case ID_VIEW_APPLOOK_WINDOWS_7: CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows7)); CDockingManager::SetDockingMode(DT_SMART); break; default: switch (theApp.m_nAppLook) { case ID_VIEW_APPLOOK_OFF_2007_BLUE: CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_LunaBlue); break; case ID_VIEW_APPLOOK_OFF_2007_BLACK: CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_ObsidianBlack); break; case ID_VIEW_APPLOOK_OFF_2007_SILVER: CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_Silver); break; case ID_VIEW_APPLOOK_OFF_2007_AQUA: CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_Aqua); break; } CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOffice2007)); CDockingManager::SetDockingMode(DT_SMART); } RedrawWindow(NULL, NULL, RDW_ALLCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW | RDW_FRAME | RDW_ERASE); theApp.WriteInt(_T("ApplicationLook"), theApp.m_nAppLook); } void CMainFrame::OnUpdateApplicationLook(CCmdUI* pCmdUI) { pCmdUI->SetRadio(theApp.m_nAppLook == pCmdUI->m_nID); } BOOL CMainFrame::LoadFrame(UINT nIDResource, DWORD dwDefaultStyle, CWnd* pParentWnd, CCreateContext* pContext) { // base class does the real work if (!CMDIFrameWndEx::LoadFrame(nIDResource, dwDefaultStyle, pParentWnd, pContext)) { return FALSE; } // enable customization button for all user toolbars BOOL bNameValid; CString strCustomize; bNameValid = strCustomize.LoadString(IDS_TOOLBAR_CUSTOMIZE); ASSERT(bNameValid); for (int i = 0; i < iMaxUserToolbars; i ++) { CMFCToolBar* pUserToolbar = GetUserToolBarByIndex(i); if (pUserToolbar != NULL) { pUserToolbar->EnableCustomizeButton(TRUE, ID_VIEW_CUSTOMIZE, strCustomize); } } return TRUE; } void CMainFrame::OnSettingChange(UINT uFlags, LPCTSTR lpszSection) { CMDIFrameWndEx::OnSettingChange(uFlags, lpszSection); m_wndOutput.UpdateFonts(); }
zzh-project-test
trunk/GoogleCodeTest/GoogleCodeTest/MainFrm.cpp
C++
asf20
14,249