app_Main.py 476 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # Modified by Marius Stanciu (2019) #
  8. # ###########################################################
  9. import urllib.request
  10. import urllib.parse
  11. import urllib.error
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import shutil
  16. import lzma
  17. from datetime import datetime
  18. import time
  19. import ctypes
  20. import traceback
  21. from shapely.geometry import Point, MultiPolygon
  22. from shapely.ops import unary_union
  23. from io import StringIO
  24. from reportlab.graphics import renderPDF
  25. from reportlab.pdfgen import canvas
  26. from reportlab.lib.units import inch, mm
  27. from reportlab.lib.pagesizes import landscape, portrait
  28. from svglib.svglib import svg2rlg
  29. import gc
  30. from xml.dom.minidom import parseString as parse_xml_string
  31. from multiprocessing.connection import Listener, Client
  32. from multiprocessing import Pool
  33. import socket
  34. # ####################################################################################################################
  35. # ################################### Imports part of FlatCAM #############################################
  36. # ####################################################################################################################
  37. # Various
  38. from appCommon.Common import LoudDict
  39. from appCommon.Common import color_variant
  40. from appCommon.Common import ExclusionAreas
  41. from Bookmark import BookmarkManager
  42. from appDatabase import ToolsDB2
  43. from vispy.gloo.util import _screenshot
  44. from vispy.io import write_png
  45. # FlatCAM defaults (preferences)
  46. from defaults import FlatCAMDefaults
  47. # FlatCAM Objects
  48. from appGUI.preferences.OptionsGroupUI import OptionsGroupUI
  49. from appGUI.preferences.PreferencesUIManager import PreferencesUIManager
  50. from appObjects.ObjectCollection import *
  51. from appObjects.FlatCAMObj import FlatCAMObj
  52. from appObjects.AppObject import AppObject
  53. # FlatCAM Parsing files
  54. from appParsers.ParseExcellon import Excellon
  55. from appParsers.ParseGerber import Gerber
  56. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  57. # FlatCAM appGUI
  58. from appGUI.PlotCanvas import *
  59. from appGUI.PlotCanvasLegacy import *
  60. from appGUI.MainGUI import *
  61. from appGUI.GUIElements import FCFileSaveDialog, message_dialog, FlatCAMSystemTray, FCInputDialogSlider
  62. # FlatCAM Pre-processors
  63. from appPreProcessor import load_preprocessors
  64. # FlatCAM appEditors
  65. from appEditors.AppGeoEditor import AppGeoEditor
  66. from appEditors.AppExcEditor import AppExcEditor
  67. from appEditors.AppGerberEditor import AppGerberEditor
  68. from appEditors.AppTextEditor import AppTextEditor
  69. from appEditors.appGCodeEditor import AppGCodeEditor
  70. from appParsers.ParseHPGL2 import HPGL2
  71. # FlatCAM Workers
  72. from appProcess import *
  73. from appWorkerStack import WorkerStack
  74. # FlatCAM Tools
  75. from appTools import *
  76. # FlatCAM Translation
  77. import gettext
  78. import appTranslation as fcTranslate
  79. import builtins
  80. if sys.platform == 'win32':
  81. import winreg
  82. from win32comext.shell import shell, shellcon
  83. fcTranslate.apply_language('strings')
  84. if '_' not in builtins.__dict__:
  85. _ = gettext.gettext
  86. class App(QtCore.QObject):
  87. """
  88. The main application class. The constructor starts the GUI and all other classes used by the program.
  89. """
  90. # ###############################################################################################################
  91. # ########################################## App ################################################################
  92. # ###############################################################################################################
  93. # ###############################################################################################################
  94. # ######################################### LOGGING #############################################################
  95. # ###############################################################################################################
  96. log = logging.getLogger('base')
  97. log.setLevel(logging.DEBUG)
  98. # log.setLevel(logging.WARNING)
  99. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  100. handler = logging.StreamHandler()
  101. handler.setFormatter(formatter)
  102. log.addHandler(handler)
  103. # ###############################################################################################################
  104. # #################################### Get Cmd Line Options #####################################################
  105. # ###############################################################################################################
  106. cmd_line_shellfile = ''
  107. cmd_line_shellvar = ''
  108. cmd_line_headless = None
  109. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  110. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  111. "FlatCam.py --headless=1"
  112. try:
  113. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  114. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  115. "shellvar=",
  116. "headless=",
  117. "multiprocessing-fork="])
  118. except getopt.GetoptError:
  119. print(cmd_line_help)
  120. sys.exit(2)
  121. for opt, arg in cmd_line_options:
  122. if opt == '-h':
  123. print(cmd_line_help)
  124. sys.exit()
  125. elif opt == '--shellfile':
  126. cmd_line_shellfile = arg
  127. elif opt == '--shellvar':
  128. cmd_line_shellvar = arg
  129. elif opt == '--headless':
  130. try:
  131. cmd_line_headless = eval(arg)
  132. except NameError:
  133. pass
  134. # ###############################################################################################################
  135. # ################################### Version and VERSION DATE ##################################################
  136. # ###############################################################################################################
  137. # version = "Unstable Version"
  138. version = 8.994
  139. version_date = "2020/10/30"
  140. beta = True
  141. engine = '3D'
  142. # current date now
  143. date = str(datetime.today()).rpartition('.')[0]
  144. date = ''.join(c for c in date if c not in ':-')
  145. date = date.replace(' ', '_')
  146. # ###############################################################################################################
  147. # ############################################ URLS's ###########################################################
  148. # ###############################################################################################################
  149. # URL for update checks and statistics
  150. version_url = "http://flatcam.org/version"
  151. # App URL
  152. app_url = "http://flatcam.org"
  153. # Manual URL
  154. manual_url = "http://flatcam.org/manual/index.html"
  155. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  156. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  157. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  158. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  159. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  160. # this variable will hold the project status
  161. # if True it will mean that the project was modified and not saved
  162. should_we_save = False
  163. # flag is True if saving action has been triggered
  164. save_in_progress = False
  165. # ###############################################################################################################
  166. # ####################################### APP Signals ######################################################
  167. # ###############################################################################################################
  168. # Inform the user
  169. # Handled by: App.info() --> Print on the status bar
  170. inform = QtCore.pyqtSignal([str], [str, bool])
  171. # Handled by: App.info_shell() --> Print on the shell
  172. inform_shell = QtCore.pyqtSignal([str], [str, bool])
  173. app_quit = QtCore.pyqtSignal()
  174. # General purpose background task
  175. worker_task = QtCore.pyqtSignal(dict)
  176. # File opened
  177. # Handled by:
  178. # * register_folder()
  179. # * register_recent()
  180. # Note: Setting the parameters to unicode does not seem
  181. # to have an effect. Then are received as Qstring
  182. # anyway.
  183. # File type and filename
  184. file_opened = QtCore.pyqtSignal(str, str)
  185. # File type and filename
  186. file_saved = QtCore.pyqtSignal(str, str)
  187. # Percentage of progress
  188. progress = QtCore.pyqtSignal(int)
  189. # Emitted when a new object has been added or deleted from/to the collection
  190. object_status_changed = QtCore.pyqtSignal(object, str, str)
  191. message = QtCore.pyqtSignal(str, str, str)
  192. # Emmited when shell command is finished(one command only)
  193. shell_command_finished = QtCore.pyqtSignal(object)
  194. # Emitted when multiprocess pool has been recreated
  195. pool_recreated = QtCore.pyqtSignal(object)
  196. # Emitted when an unhandled exception happens
  197. # in the worker task.
  198. thread_exception = QtCore.pyqtSignal(object)
  199. # used to signal that there are arguments for the app
  200. args_at_startup = QtCore.pyqtSignal(list)
  201. # a reusable signal to replot a list of objects
  202. # should be disconnected after use so it can be reused
  203. replot_signal = pyqtSignal(list)
  204. # signal emitted when jumping
  205. jump_signal = pyqtSignal(tuple)
  206. # signal emitted when jumping
  207. locate_signal = pyqtSignal(tuple, str)
  208. # close app signal
  209. close_app_signal = pyqtSignal()
  210. # will perform the cleanup operation after a Graceful Exit
  211. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  212. # graphic residues behind
  213. cleanup = pyqtSignal()
  214. def __init__(self, qapp, user_defaults=True):
  215. """
  216. Starts the application.
  217. :return: app
  218. :rtype: App
  219. """
  220. super().__init__()
  221. log.info("FlatCAM Starting...")
  222. self.qapp = qapp
  223. # declare it here so there is a reference
  224. self.f_handlers = lambda: None
  225. # ############################################################################################################
  226. # ################# Setup the listening thread for another instance launching with args ######################
  227. # ############################################################################################################
  228. if sys.platform == 'win32' or sys.platform == 'linux':
  229. # make sure the thread is stored by using a self. otherwise it's garbage collected
  230. self.listen_th = QtCore.QThread()
  231. self.listen_th.start(priority=QtCore.QThread.LowestPriority)
  232. self.new_launch = ArgsThread()
  233. self.new_launch.open_signal[list].connect(self.on_startup_args)
  234. self.new_launch.moveToThread(self.listen_th)
  235. self.new_launch.start.emit()
  236. # ############################################################################################################
  237. # ########################################## OS-specific #####################################################
  238. # ############################################################################################################
  239. portable = False
  240. # Folder for user settings.
  241. if sys.platform == 'win32':
  242. if platform.architecture()[0] == '32bit':
  243. self.log.debug("Win32!")
  244. else:
  245. self.log.debug("Win64!")
  246. # #######################################################################################################
  247. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  248. # #######################################################################################################
  249. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  250. try:
  251. with open(config_file, 'r'):
  252. pass
  253. except FileNotFoundError:
  254. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  255. try:
  256. with open(config_file, 'r') as f:
  257. try:
  258. for line in f:
  259. param = str(line).replace('\n', '').rpartition('=')
  260. if param[0] == 'portable':
  261. try:
  262. portable = eval(param[2])
  263. except NameError:
  264. portable = False
  265. if param[0] == 'headless':
  266. if param[2].lower() == 'true':
  267. self.cmd_line_headless = 1
  268. else:
  269. self.cmd_line_headless = None
  270. except Exception as e:
  271. self.log.debug('App.__init__() -->%s' % str(e))
  272. return
  273. except FileNotFoundError as e:
  274. self.log.debug(str(e))
  275. pass
  276. if portable is False:
  277. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  278. else:
  279. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  280. self.os = 'windows'
  281. else: # Linux/Unix/MacOS
  282. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  283. self.os = 'unix'
  284. # ############################################################################################################
  285. # ################################# Setup folders and files ##################################################
  286. # ############################################################################################################
  287. if not os.path.exists(self.data_path):
  288. os.makedirs(self.data_path)
  289. self.log.debug('Created data folder: ' + self.data_path)
  290. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  291. self.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  292. self.preprocessorpaths = self.preprocessors_path()
  293. if not os.path.exists(self.preprocessorpaths):
  294. os.makedirs(self.preprocessorpaths)
  295. self.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  296. # create tools_db.FlatDB file if there is none
  297. db_path = self.tools_database_path()
  298. try:
  299. f = open(db_path)
  300. f.close()
  301. except IOError:
  302. self.log.debug('Creating empty tools_db.FlatDB')
  303. f = open(db_path, 'w')
  304. json.dump({}, f)
  305. f.close()
  306. # create current_defaults.FlatConfig file if there is none
  307. def_path = self.defaults_path()
  308. try:
  309. f = open(def_path)
  310. f.close()
  311. except IOError:
  312. self.log.debug('Creating empty current_defaults.FlatConfig')
  313. f = open(def_path, 'w')
  314. json.dump({}, f)
  315. f.close()
  316. # the factory defaults are written only once at the first launch of the application after installation
  317. FlatCAMDefaults.save_factory_defaults(self.factory_defaults_path(), self.version)
  318. # create a recent files json file if there is none
  319. rec_f_path = self.recent_files_path()
  320. try:
  321. f = open(rec_f_path)
  322. f.close()
  323. except IOError:
  324. self.log.debug('Creating empty recent.json')
  325. f = open(rec_f_path, 'w')
  326. json.dump([], f)
  327. f.close()
  328. # create a recent projects json file if there is none
  329. rec_proj_path = self.recent_projects_path()
  330. try:
  331. fp = open(rec_proj_path)
  332. fp.close()
  333. except IOError:
  334. self.log.debug('Creating empty recent_projects.json')
  335. fp = open(rec_proj_path, 'w')
  336. json.dump([], fp)
  337. fp.close()
  338. # Application directory. CHDIR to it. Otherwise, trying to load GUI icons will fail as their path is relative.
  339. # This will fail under cx_freeze ...
  340. self.app_home = os.path.dirname(os.path.realpath(__file__))
  341. self.log.debug("Application path is " + self.app_home)
  342. self.log.debug("Started in " + os.getcwd())
  343. # cx_freeze workaround
  344. if os.path.isfile(self.app_home):
  345. self.app_home = os.path.dirname(self.app_home)
  346. os.chdir(self.app_home)
  347. # ############################################################################################################
  348. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  349. # ############################################################################################################
  350. self.defaults = FlatCAMDefaults(beta=self.beta, version=self.version)
  351. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  352. if user_defaults:
  353. self.defaults.load(filename=current_defaults_path, inform=self.inform)
  354. if self.defaults['units'] == 'MM':
  355. self.decimals = int(self.defaults['decimals_metric'])
  356. else:
  357. self.decimals = int(self.defaults['decimals_inch'])
  358. if self.defaults["global_gray_icons"] is False:
  359. self.resource_location = 'assets/resources'
  360. else:
  361. self.resource_location = 'assets/resources/dark_resources'
  362. self.current_units = self.defaults['units']
  363. # ###########################################################################################################
  364. # #################################### SETUP OBJECT CLASSES #################################################
  365. # ###########################################################################################################
  366. self.setup_obj_classes()
  367. # ###########################################################################################################
  368. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  369. # ###########################################################################################################
  370. self.pool = Pool()
  371. # ###########################################################################################################
  372. # ###################################### Clear GUI Settings - once at first start ###########################
  373. # ###########################################################################################################
  374. if self.defaults["first_run"] is True:
  375. # on first run clear the previous QSettings, therefore clearing the GUI settings
  376. qsettings = QSettings("Open Source", "FlatCAM")
  377. for key in qsettings.allKeys():
  378. qsettings.remove(key)
  379. # This will write the setting to the platform specific storage.
  380. del qsettings
  381. # ###########################################################################################################
  382. # ###################################### Setting the Splash Screen ##########################################
  383. # ###########################################################################################################
  384. splash_settings = QSettings("Open Source", "FlatCAM")
  385. if splash_settings.contains("splash_screen"):
  386. show_splash = splash_settings.value("splash_screen")
  387. else:
  388. splash_settings.setValue('splash_screen', 1)
  389. # This will write the setting to the platform specific storage.
  390. del splash_settings
  391. show_splash = 1
  392. if show_splash and self.cmd_line_headless != 1:
  393. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  394. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  395. # self.splash.setMask(splash_pix.mask())
  396. # move splashscreen to the current monitor
  397. desktop = QtWidgets.QApplication.desktop()
  398. screen = desktop.screenNumber(QtGui.QCursor.pos())
  399. current_screen_center = desktop.availableGeometry(screen).center()
  400. self.splash.move(current_screen_center - self.splash.rect().center())
  401. self.splash.show()
  402. self.splash.showMessage(_("The application is initializing ..."),
  403. alignment=Qt.AlignBottom | Qt.AlignLeft,
  404. color=QtGui.QColor("gray"))
  405. else:
  406. self.splash = None
  407. show_splash = 0
  408. # ###########################################################################################################
  409. # ######################################### Initialize GUI ##################################################
  410. # ###########################################################################################################
  411. # FlatCAM colors used in plotting
  412. self.FC_light_green = '#BBF268BF'
  413. self.FC_dark_green = '#006E20BF'
  414. self.FC_light_blue = '#a5a5ffbf'
  415. self.FC_dark_blue = '#0000ffbf'
  416. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  417. if theme_settings.contains("theme"):
  418. theme = theme_settings.value('theme', type=str)
  419. else:
  420. theme = 'white'
  421. if self.defaults["global_cursor_color_enabled"]:
  422. self.cursor_color_3D = self.defaults["global_cursor_color"]
  423. else:
  424. if theme == 'white':
  425. self.cursor_color_3D = 'black'
  426. else:
  427. self.cursor_color_3D = 'gray'
  428. # update the defaults dict with the setting in QSetting
  429. self.defaults['global_theme'] = theme
  430. self.ui = MainGUI(self)
  431. # set FlatCAM units in the Status bar
  432. self.set_screen_units(self.defaults['units'])
  433. # ###########################################################################################################
  434. # ########################################### AUTOSAVE SETUP ################################################
  435. # ###########################################################################################################
  436. self.block_autosave = False
  437. self.autosave_timer = QtCore.QTimer(self)
  438. self.save_project_auto_update()
  439. self.autosave_timer.timeout.connect(self.save_project_auto)
  440. # ###########################################################################################################
  441. # #################################### LOAD PREPROCESSORS ###################################################
  442. # ###########################################################################################################
  443. # ----------------------------------------- WARNING --------------------------------------------------------
  444. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  445. # That's because the number of preprocessors can vary and here the comboboxes are populated
  446. # -----------------------------------------------------------------------------------------------------------
  447. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  448. # the preprocessor file
  449. self.preprocessors = load_preprocessors(self)
  450. # make sure that always the 'default' preprocessor is the first item in the dictionary
  451. if 'default' in self.preprocessors.keys():
  452. new_ppp_dict = {}
  453. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  454. default_pp = self.preprocessors.pop('default')
  455. new_ppp_dict['default'] = default_pp
  456. # then add the rest of the keys
  457. for name, val_class in self.preprocessors.items():
  458. new_ppp_dict[name] = val_class
  459. # and now put back the ordered dict with 'default' key first
  460. self.preprocessors = new_ppp_dict
  461. # populate the Preprocessor ComboBoxes in the PREFERENCES
  462. for name in list(self.preprocessors.keys()):
  463. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  464. if name.partition('_')[0] == 'Paste':
  465. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  466. continue
  467. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  468. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  469. if name == 'hpgl':
  470. continue
  471. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.addItem(name)
  472. # add ToolTips for the Preprocessor ComboBoxes in Preferences
  473. for it in range(self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.count()):
  474. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.setItemData(
  475. it, self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.itemText(it), QtCore.Qt.ToolTipRole)
  476. for it in range(self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.count()):
  477. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.setItemData(
  478. it, self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.itemText(it),
  479. QtCore.Qt.ToolTipRole)
  480. for it in range(self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.count()):
  481. self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.setItemData(
  482. it, self.ui.tools_defaults_form.tools_drill_group.pp_excellon_name_cb.itemText(it),
  483. QtCore.Qt.ToolTipRole)
  484. # ###########################################################################################################
  485. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  486. # ###########################################################################################################
  487. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  488. inform=self.inform)
  489. self.preferencesUiManager.defaults_write_form()
  490. # When the self.defaults dictionary changes will update the Preferences GUI forms
  491. self.defaults.set_change_callback(self.on_defaults_dict_change)
  492. # ###########################################################################################################
  493. # ##################################### FIRST RUN SECTION ###################################################
  494. # ################################ It's done only once after install #####################################
  495. # ###########################################################################################################
  496. if self.defaults["first_run"] is True:
  497. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'minimal'
  498. initial_lay = 'minimal'
  499. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  500. # Set the combobox in Preferences to the current layout
  501. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  502. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  503. # after the first run, this object should be False
  504. self.defaults["first_run"] = False
  505. self.preferencesUiManager.save_defaults(silent=True)
  506. # ###########################################################################################################
  507. # ############################################ Data #########################################################
  508. # ###########################################################################################################
  509. self.recent = []
  510. self.recent_projects = []
  511. self.clipboard = QtWidgets.QApplication.clipboard()
  512. self.project_filename = None
  513. self.toggle_units_ignore = False
  514. self.main_thread = QtWidgets.QApplication.instance().thread()
  515. # ###########################################################################################################
  516. # ########################################## LOAD LANGUAGES ################################################
  517. # ###########################################################################################################
  518. self.languages = fcTranslate.load_languages()
  519. for name in sorted(self.languages.values()):
  520. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  521. # ###########################################################################################################
  522. # ####################################### APPLY APP LANGUAGE ################################################
  523. # ###########################################################################################################
  524. ret_val = fcTranslate.apply_language('strings')
  525. if ret_val == "no language":
  526. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  527. self.log.debug("Could not find the Language files. The App strings are missing.")
  528. else:
  529. # make the current language the current selection on the language combobox
  530. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  531. self.log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  532. # ###########################################################################################################
  533. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  534. # ###########################################################################################################
  535. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  536. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  537. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  538. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  539. self.defaults.propagate_defaults()
  540. # ###########################################################################################################
  541. # ######################################## UPDATE THE OPTIONS ###############################################
  542. # ###########################################################################################################
  543. self.options = LoudDict()
  544. # -----------------------------------------------------------------------------------------------------------
  545. # Update the self.options from the self.defaults
  546. # The self.defaults holds the application defaults while the self.options holds the object defaults
  547. # -----------------------------------------------------------------------------------------------------------
  548. # Copy app defaults to project options
  549. for def_key, def_val in self.defaults.items():
  550. self.options[def_key] = deepcopy(def_val)
  551. self.preferencesUiManager.show_preferences_gui()
  552. # ### End of Data ####
  553. # ###########################################################################################################
  554. # #################################### SETUP OBJECT COLLECTION ##############################################
  555. # ###########################################################################################################
  556. self.collection = ObjectCollection(app=self)
  557. self.ui.project_tab_layout.addWidget(self.collection.view)
  558. self.app_obj = AppObject(app=self)
  559. # ### Adjust tabs width ## ##
  560. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  561. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  562. self.collection.view.setMinimumWidth(290)
  563. self.log.debug("Finished creating Object Collection.")
  564. # ###########################################################################################################
  565. # ######################################## SETUP Plot Area ##################################################
  566. # ###########################################################################################################
  567. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  568. if self.defaults["global_graphic_engine"] == '3D':
  569. self.is_legacy = False
  570. else:
  571. self.is_legacy = True
  572. # Event signals disconnect id holders
  573. self.mp = None
  574. self.mm = None
  575. self.mr = None
  576. self.mdc = None
  577. self.mp_zc = None
  578. self.kp = None
  579. # Matplotlib axis
  580. self.axes = None
  581. if show_splash:
  582. self.splash.showMessage(_("The application is initializing ...\n"
  583. "Canvas initialization started."),
  584. alignment=Qt.AlignBottom | Qt.AlignLeft,
  585. color=QtGui.QColor("gray"))
  586. start_plot_time = time.time() # debug
  587. self.plotcanvas = None
  588. self.app_cursor = None
  589. self.hover_shapes = None
  590. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  591. # setup the PlotCanvas
  592. self.on_plotcanvas_setup()
  593. end_plot_time = time.time()
  594. self.used_time = end_plot_time - start_plot_time
  595. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  596. if show_splash:
  597. self.splash.showMessage('%s: %ssec' % (_("The application is initializing ...\n"
  598. "Canvas initialization started.\n"
  599. "Canvas initialization finished in"), '%.2f' % self.used_time),
  600. alignment=Qt.AlignBottom | Qt.AlignLeft,
  601. color=QtGui.QColor("gray"))
  602. self.ui.splitter.setStretchFactor(1, 2)
  603. # ###########################################################################################################
  604. # ############################################### Worker SETUP ##############################################
  605. # ###########################################################################################################
  606. if self.defaults["global_worker_number"]:
  607. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  608. else:
  609. self.workers = WorkerStack(workers_number=2)
  610. self.worker_task.connect(self.workers.add_task)
  611. self.log.debug("Finished creating Workers crew.")
  612. # ###########################################################################################################
  613. # ############################################# Activity Monitor ############################################
  614. # ###########################################################################################################
  615. # self.activity_view = FlatCAMActivityView(app=self)
  616. # self.ui.infobar.addWidget(self.activity_view)
  617. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  618. # ###########################################################################################################
  619. # ########################################## Other setups ###################################################
  620. # ###########################################################################################################
  621. # to use for tools like Distance tool who depends on the event sources who are changed inside the appEditors
  622. # depending on from where those tools are called different actions can be done
  623. self.call_source = 'app'
  624. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  625. self.tool_tab_locked = False
  626. # decide if to show or hide the Notebook side of the screen at startup
  627. if self.defaults["global_project_at_startup"] is True:
  628. self.ui.splitter.setSizes([1, 1])
  629. else:
  630. self.ui.splitter.setSizes([0, 1])
  631. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  632. self.setup_default_properties_tab()
  633. # ###########################################################################################################
  634. # ####################################### Auto-complete KEYWORDS ############################################
  635. # ###########################################################################################################
  636. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  637. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  638. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  639. 'export_exc',
  640. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  641. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  642. 'interiors', 'isolate', 'join_excellon',
  643. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  644. 'mirror', 'ncc',
  645. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  646. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  647. 'options', 'origin',
  648. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  649. 'save', 'save_project',
  650. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  651. 'skew', 'subtract_poly', 'subtract_rectangle',
  652. 'version', 'write_gcode'
  653. ]
  654. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  655. 'Paste_1',
  656. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  657. 'Toolchange_manual', 'True', 'Users',
  658. 'all', 'auto', 'axis',
  659. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  660. 'contour', 'default',
  661. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  662. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  663. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  664. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  665. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  666. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  667. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  668. 'spacing_columns',
  669. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  670. 'toolchange_xy', 'toolchangez', 'travelz',
  671. 'tooldia', 'use_threads', 'value',
  672. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  673. ]
  674. self.tcl_keywords = [
  675. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  676. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  677. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  678. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  679. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  680. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  681. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  682. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  683. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  684. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  685. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  686. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  687. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  688. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  689. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  690. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  691. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  692. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  693. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  694. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  695. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  696. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  697. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  698. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  699. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  700. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  701. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  702. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  703. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  704. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  705. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  706. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  707. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  708. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  709. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  710. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  711. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  712. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  713. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  714. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  715. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  716. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  717. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  718. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  719. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  720. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  721. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  722. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  723. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  724. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  725. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  726. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  727. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  728. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  729. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  730. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  731. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  732. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  733. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  734. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  735. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  736. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  737. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  738. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  739. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  740. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  741. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  742. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  743. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  744. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  745. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  746. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  747. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  748. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  749. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  750. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  751. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  752. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  753. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  754. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  755. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  756. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  757. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  758. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  759. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  760. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  761. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  762. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  763. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  764. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  765. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  766. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  767. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  768. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  769. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  770. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  771. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  772. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  773. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  774. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  775. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  776. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  777. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  778. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  779. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  780. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  781. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  782. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  783. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  784. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  785. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  786. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  787. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  788. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  789. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  790. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  791. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  792. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  793. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  794. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  795. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  796. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  797. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  798. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  799. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  800. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  801. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  802. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  803. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  804. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  805. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  806. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  807. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  808. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  809. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  810. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  811. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  812. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  813. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  814. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  815. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  816. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  817. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  818. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  819. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  820. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  821. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  822. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  823. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  824. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  825. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  826. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  827. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  828. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  829. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  830. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  831. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  832. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  833. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  834. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  835. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  836. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  837. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  838. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  839. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  840. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  841. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  842. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  843. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  844. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  845. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  846. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  847. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  848. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  849. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  850. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  851. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  852. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  853. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  854. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  855. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  856. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  857. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  858. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  859. ]
  860. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  861. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  862. # ###########################################################################################################
  863. # ########################################## Tools and Plugins ##############################################
  864. # ###########################################################################################################
  865. self.shell = None
  866. self.dblsidedtool = None
  867. self.distance_tool = None
  868. self.distance_min_tool = None
  869. self.panelize_tool = None
  870. self.film_tool = None
  871. self.paste_tool = None
  872. self.calculator_tool = None
  873. self.rules_tool = None
  874. self.sub_tool = None
  875. self.move_tool = None
  876. self.cutout_tool = None
  877. self.ncclear_tool = None
  878. self.paint_tool = None
  879. self.isolation_tool = None
  880. self.drilling_tool = None
  881. self.optimal_tool = None
  882. self.transform_tool = None
  883. self.properties_tool = None
  884. self.pdf_tool = None
  885. self.image_tool = None
  886. self.pcb_wizard_tool = None
  887. self.cal_exc_tool = None
  888. self.qrcode_tool = None
  889. self.copper_thieving_tool = None
  890. self.fiducial_tool = None
  891. self.edrills_tool = None
  892. self.align_objects_tool = None
  893. self.punch_tool = None
  894. self.invert_tool = None
  895. self.corners_tool = None
  896. self.etch_tool = None
  897. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  898. try:
  899. self.install_tools()
  900. except AttributeError as e:
  901. self.log.debug("App.__init__() install_tools() --> %s" % str(e))
  902. # ###########################################################################################################
  903. # ######################################### BookMarks Manager ###############################################
  904. # ###########################################################################################################
  905. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  906. self.install_bookmarks()
  907. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  908. # ###########################################################################################################
  909. # ########################################### Tools Database ################################################
  910. # ###########################################################################################################
  911. self.tools_db_tab = None
  912. # ### System Font Parsing ###
  913. # self.f_parse = ParseFont(self)
  914. # self.parse_system_fonts()
  915. # ###########################################################################################################
  916. # ############################################## Shell SETUP ################################################
  917. # ###########################################################################################################
  918. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  919. if self.defaults["global_shell_at_startup"]:
  920. self.ui.shell_dock.show()
  921. else:
  922. self.ui.shell_dock.hide()
  923. # ###########################################################################################################
  924. # ######################################### Check for updates ###############################################
  925. # ###########################################################################################################
  926. # Separate thread (Not worker)
  927. # Check for updates on startup but only if the user consent and the app is not in Beta version
  928. if (self.beta is False or self.beta is None) and \
  929. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  930. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  931. # self.thr2 = QtCore.QThread()
  932. self.worker_task.emit({'fcn': self.version_check,
  933. 'params': []})
  934. # self.thr2.start(QtCore.QThread.LowPriority)
  935. # ###########################################################################################################
  936. # ##################################### Register files with FlatCAM; #######################################
  937. # ################################### It works only for Windows for now ####################################
  938. # ###########################################################################################################
  939. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  940. self.on_register_files()
  941. # ###########################################################################################################
  942. # ######################################## Variables for global usage #######################################
  943. # ###########################################################################################################
  944. # hold the App units
  945. self.units = 'MM'
  946. # coordinates for relative position display
  947. self.rel_point1 = (0, 0)
  948. self.rel_point2 = (0, 0)
  949. # variable to store coordinates
  950. self.pos = (0, 0)
  951. self.pos_canvas = (0, 0)
  952. self.pos_jump = (0, 0)
  953. # variable to store mouse coordinates
  954. self.mouse = [0, 0]
  955. # variable to store the delta positions on cavnas
  956. self.dx = 0
  957. self.dy = 0
  958. # decide if we have a double click or single click
  959. self.doubleclick = False
  960. # store here the is_dragging value
  961. self.event_is_dragging = False
  962. # variable to store if a command is active (then the var is not None) and which one it is
  963. self.command_active = None
  964. # variable to store the status of moving selection action
  965. # None value means that it's not an selection action
  966. # True value = a selection from left to right
  967. # False value = a selection from right to left
  968. self.selection_type = None
  969. # List to store the objects that are currently loaded in FlatCAM
  970. # This list is updated on each object creation or object delete
  971. self.all_objects_list = []
  972. self.objects_under_the_click_list = []
  973. # List to store the objects that are selected
  974. self.sel_objects_list = []
  975. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  976. self.key_modifiers = None
  977. # Variable to store the status of the code editor
  978. self.toggle_codeeditor = False
  979. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  980. self.click_noproject = False
  981. self.cursor = None
  982. # Variable to store the GCODE that was edited
  983. self.gcode_edited = ""
  984. # Variable to store old state of the Tools Toolbar; used in the Editor2Object and in Object2Editor methods
  985. self.old_state_of_tools_toolbar = False
  986. self.text_editor_tab = None
  987. # reference for the self.ui.code_editor
  988. self.reference_code_editor = None
  989. self.script_code = ''
  990. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  991. self.tools_db_changed_flag = False
  992. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  993. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  994. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  995. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  996. 'tsm']
  997. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  998. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  999. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1000. 'sbp', 'tap', 'xpi']
  1001. self.svg_list = ['svg']
  1002. self.dxf_list = ['dxf']
  1003. self.pdf_list = ['pdf']
  1004. self.prj_list = ['flatprj']
  1005. self.conf_list = ['flatconfig']
  1006. # last used filters
  1007. self.last_op_gerber_filter = None
  1008. self.last_op_excellon_filter = None
  1009. self.last_op_gcode_filter = None
  1010. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1011. # flag for polygons not cleared
  1012. self.poly_not_cleared = False
  1013. # VisPy visuals
  1014. self.isHovering = False
  1015. self.notHovering = True
  1016. # Window geometry
  1017. self.x_pos = None
  1018. self.y_pos = None
  1019. self.width = None
  1020. self.height = None
  1021. # when True, the app has to return from any thread
  1022. self.abort_flag = False
  1023. # set the value used in the Windows Title
  1024. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1025. # this holds a widget that is installed in the Plot Area when View Source option is used
  1026. self.source_editor_tab = None
  1027. self.pagesize = {}
  1028. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1029. # VisPy visuals
  1030. if self.is_legacy is False:
  1031. try:
  1032. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1033. except AttributeError:
  1034. self.tool_shapes = None
  1035. else:
  1036. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1037. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1038. # used in the delayed shutdown self.start_delayed_quit() method
  1039. self.save_timer = None
  1040. # ###########################################################################################################
  1041. # ################################## ADDING FlatCAM EDITORS section #########################################
  1042. # ###########################################################################################################
  1043. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1044. # at the first launch of the App , the editors will not be functional.
  1045. try:
  1046. self.geo_editor = AppGeoEditor(self)
  1047. except Exception as es:
  1048. self.log.debug("app_Main.__init__() --> Geo Editor Error: %s" % str(es))
  1049. try:
  1050. self.exc_editor = AppExcEditor(self)
  1051. except Exception as es:
  1052. self.log.debug("app_Main.__init__() --> Excellon Editor Error: %s" % str(es))
  1053. try:
  1054. self.grb_editor = AppGerberEditor(self)
  1055. except Exception as es:
  1056. self.log.debug("app_Main.__init__() --> Gerber Editor Error: %s" % str(es))
  1057. try:
  1058. self.gcode_editor = AppGCodeEditor(self)
  1059. except Exception as es:
  1060. self.log.debug("app_Main.__init__() --> GCode Editor Error: %s" % str(es))
  1061. self.log.debug("Finished adding FlatCAM Editor's.")
  1062. self.ui.set_ui_title(name=_("New Project - Not saved"))
  1063. current_platform = platform.architecture()[0]
  1064. if current_platform != '64bit':
  1065. # set Excellon path optimizations algorithm to TSA if the app is run on a 32bit platform
  1066. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1067. if self.defaults['excellon_optimization_type'] in ['M', 'B']:
  1068. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1069. # set Geometry path optimizations algorithm to Rtree if the app is run on a 32bit platform
  1070. # modes 'M' or 'B' are not allowed when the app is running in 32bit platform
  1071. if self.defaults['geometry_optimization_type'] in ['M', 'B']:
  1072. self.ui.geometry_defaults_form.geometry_gen_group.opt_algorithm_radio.set_value('R')
  1073. # ###########################################################################################################
  1074. # ########################################### EXCLUSION AREAS ###############################################
  1075. # ###########################################################################################################
  1076. self.exc_areas = ExclusionAreas(app=self)
  1077. # ###########################################################################################################
  1078. # ###########################################################################################################
  1079. # ###################################### INSTANTIATE CLASSES THAT HOLD THE MENU HANDLERS ####################
  1080. # ###########################################################################################################
  1081. # ###########################################################################################################
  1082. self.f_handlers = MenuFileHandlers(app=self)
  1083. # this is calculated in the class above (somehow?)
  1084. self.defaults["root_folder_path"] = self.app_home
  1085. # ###########################################################################################################
  1086. # ############################################### SYS TRAY ##################################################
  1087. # ###########################################################################################################
  1088. if self.defaults["global_systray_icon"]:
  1089. self.parent_w = QtWidgets.QWidget()
  1090. if self.cmd_line_headless == 1:
  1091. self.trayIcon = FlatCAMSystemTray(app=self,
  1092. icon=QtGui.QIcon(self.resource_location +
  1093. '/flatcam_icon32_green.png'),
  1094. headless=True,
  1095. parent=self.parent_w)
  1096. else:
  1097. self.trayIcon = FlatCAMSystemTray(app=self,
  1098. icon=QtGui.QIcon(self.resource_location +
  1099. '/flatcam_icon32_green.png'),
  1100. parent=self.parent_w)
  1101. # ###########################################################################################################
  1102. # ############################################ SETUP RECENT ITEMS ###########################################
  1103. # ###########################################################################################################
  1104. self.setup_recent_items()
  1105. # ###########################################################################################################
  1106. # ###########################################################################################################
  1107. # ############################################# Signal handling #############################################
  1108. # ###########################################################################################################
  1109. # ###########################################################################################################
  1110. # ########################################## Custom signals ################################################
  1111. # signal for displaying messages in status bar
  1112. self.inform[str].connect(self.info)
  1113. self.inform[str, bool].connect(self.info)
  1114. # signal for displaying messages in the shell
  1115. self.inform_shell[str].connect(self.info_shell)
  1116. self.inform_shell[str, bool].connect(self.info_shell)
  1117. # signal to be called when the app is quiting
  1118. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  1119. self.message.connect(lambda: message_dialog(parent=self.ui))
  1120. # self.progress.connect(self.set_progress_bar)
  1121. # signals emitted when file state change
  1122. self.file_opened.connect(self.register_recent)
  1123. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1124. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1125. # when the defaults dictionary values change
  1126. self.defaults.defaults.set_change_callback(callback=self.on_properties_tab_click)
  1127. # ########################################## Standard signals ###############################################
  1128. # ### Menu
  1129. self.ui.menufilenewproject.triggered.connect(self.f_handlers.on_file_new_click)
  1130. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  1131. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  1132. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  1133. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  1134. self.ui.menufileopengerber.triggered.connect(self.f_handlers.on_fileopengerber)
  1135. self.ui.menufileopenexcellon.triggered.connect(self.f_handlers.on_fileopenexcellon)
  1136. self.ui.menufileopengcode.triggered.connect(self.f_handlers.on_fileopengcode)
  1137. self.ui.menufileopenproject.triggered.connect(self.f_handlers.on_file_openproject)
  1138. self.ui.menufileopenconfig.triggered.connect(self.f_handlers.on_file_openconfig)
  1139. self.ui.menufilenewscript.triggered.connect(self.f_handlers.on_filenewscript)
  1140. self.ui.menufileopenscript.triggered.connect(self.f_handlers.on_fileopenscript)
  1141. self.ui.menufileopenscriptexample.triggered.connect(self.f_handlers.on_fileopenscript_example)
  1142. self.ui.menufilerunscript.triggered.connect(self.f_handlers.on_filerunscript)
  1143. self.ui.menufileimportsvg.triggered.connect(lambda: self.f_handlers.on_file_importsvg("geometry"))
  1144. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.f_handlers.on_file_importsvg("gerber"))
  1145. self.ui.menufileimportdxf.triggered.connect(lambda: self.f_handlers.on_file_importdxf("geometry"))
  1146. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.f_handlers.on_file_importdxf("gerber"))
  1147. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.f_handlers.on_fileopenhpgl2)
  1148. self.ui.menufileexportsvg.triggered.connect(self.f_handlers.on_file_exportsvg)
  1149. self.ui.menufileexportpng.triggered.connect(self.f_handlers.on_file_exportpng)
  1150. self.ui.menufileexportexcellon.triggered.connect(self.f_handlers.on_file_exportexcellon)
  1151. self.ui.menufileexportgerber.triggered.connect(self.f_handlers.on_file_exportgerber)
  1152. self.ui.menufileexportdxf.triggered.connect(self.f_handlers.on_file_exportdxf)
  1153. self.ui.menufile_print.triggered.connect(lambda: self.f_handlers.on_file_save_objects_pdf(use_thread=True))
  1154. self.ui.menufilesaveproject.triggered.connect(self.f_handlers.on_file_saveproject)
  1155. self.ui.menufilesaveprojectas.triggered.connect(self.f_handlers.on_file_saveprojectas)
  1156. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1157. self.ui.menufilesavedefaults.triggered.connect(self.f_handlers.on_file_savedefaults)
  1158. self.ui.menufileexportpref.triggered.connect(self.f_handlers.on_export_preferences)
  1159. self.ui.menufileimportpref.triggered.connect(self.f_handlers.on_import_preferences)
  1160. self.ui.menufile_exit.triggered.connect(self.final_save)
  1161. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1162. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1163. self.ui.menuedit_join2geo.triggered.connect(self.on_edit_join)
  1164. self.ui.menuedit_join_exc2exc.triggered.connect(self.on_edit_join_exc)
  1165. self.ui.menuedit_join_grb2grb.triggered.connect(self.on_edit_join_grb)
  1166. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1167. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1168. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1169. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  1170. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1171. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1172. self.ui.menueditconvert_any2excellon.triggered.connect(self.convert_any2excellon)
  1173. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1174. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  1175. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1176. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1177. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1178. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1179. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1180. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1181. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1182. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1183. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1184. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1185. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1186. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1187. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1188. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1189. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1190. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1191. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1192. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  1193. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1194. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1195. self.ui.menuviewenableother.triggered.connect(self.enable_other_plots)
  1196. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1197. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1198. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1199. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1200. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1201. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1202. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  1203. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  1204. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  1205. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  1206. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  1207. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  1208. self.ui.menuview_toggle_grid_lines.triggered.connect(self.plotcanvas.on_toggle_grid_lines)
  1209. self.ui.menuview_toggle_axis.triggered.connect(self.plotcanvas.on_toggle_axis)
  1210. self.ui.menuview_toggle_hud.triggered.connect(self.plotcanvas.on_toggle_hud)
  1211. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1212. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1213. self.ui.menuhelp_readme.triggered.connect(self.on_howto)
  1214. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1215. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1216. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1217. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1218. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1219. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1220. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1221. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1222. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1223. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1224. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  1225. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1226. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1227. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1228. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1229. # ToolBar signals
  1230. self.connect_toolbar_signals(ui=self.ui)
  1231. # Context Menu
  1232. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1233. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  1234. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  1235. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  1236. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  1237. self.ui.popmenu_new_prj.triggered.connect(self.f_handlers.on_file_new)
  1238. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1239. self.ui.clearplot.triggered.connect(self.clear_plots)
  1240. self.ui.replot.triggered.connect(self.plot_all)
  1241. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  1242. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1243. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1244. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1245. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1246. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1247. # Project Context Menu -> Color Setting
  1248. for act in self.ui.menuprojectcolor.actions():
  1249. act.triggered.connect(self.on_set_color_action_triggered)
  1250. # Notebook tab clicking
  1251. self.ui.notebook.tabBarClicked.connect(self.on_properties_tab_click)
  1252. # ###########################################################################################################
  1253. # #################################### GUI PREFERENCES SIGNALS ##############################################
  1254. # ###########################################################################################################
  1255. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1256. lambda: self.on_toggle_units(no_pref=False))
  1257. # ##################################### Workspace Setting Signals ###########################################
  1258. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  1259. self.on_workspace_modified)
  1260. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  1261. self.on_workspace_modified
  1262. )
  1263. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1264. # ###########################################################################################################
  1265. # ######################################## GUI SETTINGS SIGNALS #############################################
  1266. # ###########################################################################################################
  1267. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1268. # ######################################## Tools related signals ############################################
  1269. # portability changed signal
  1270. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1271. # Object list
  1272. self.object_status_changed.connect(self.collection.on_collection_updated)
  1273. # when there are arguments at application startup this get launched
  1274. self.args_at_startup[list].connect(self.on_startup_args)
  1275. # ###########################################################################################################
  1276. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  1277. # ###########################################################################################################
  1278. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1279. lambda: self.restore_extensions(ext_type='excellon'))
  1280. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1281. lambda: self.restore_extensions(ext_type='gcode'))
  1282. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1283. lambda: self.restore_extensions(ext_type='gerber'))
  1284. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1285. lambda: self.delete_all_extensions(ext_type='excellon'))
  1286. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1287. lambda: self.delete_all_extensions(ext_type='gcode'))
  1288. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1289. lambda: self.delete_all_extensions(ext_type='gerber'))
  1290. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1291. lambda: self.add_extension(ext_type='excellon'))
  1292. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1293. lambda: self.add_extension(ext_type='gcode'))
  1294. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1295. lambda: self.add_extension(ext_type='gerber'))
  1296. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1297. lambda: self.del_extension(ext_type='excellon'))
  1298. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1299. lambda: self.del_extension(ext_type='gcode'))
  1300. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1301. lambda: self.del_extension(ext_type='gerber'))
  1302. # connect the 'Apply' buttons from the Preferences/File Associations
  1303. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1304. lambda: self.on_register_files(obj_type='excellon'))
  1305. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1306. lambda: self.on_register_files(obj_type='gcode'))
  1307. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1308. lambda: self.on_register_files(obj_type='gerber'))
  1309. # ###########################################################################################################
  1310. # ########################################### KEYWORDS SIGNALS ##############################################
  1311. # ###########################################################################################################
  1312. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1313. lambda: self.restore_extensions(ext_type='keyword'))
  1314. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1315. lambda: self.delete_all_extensions(ext_type='keyword'))
  1316. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1317. lambda: self.add_extension(ext_type='keyword'))
  1318. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1319. lambda: self.del_extension(ext_type='keyword'))
  1320. # ###########################################################################################################
  1321. # ########################################### GUI SIGNALS ###################################################
  1322. # ###########################################################################################################
  1323. self.ui.hud_label.clicked.connect(self.plotcanvas.on_toggle_hud)
  1324. self.ui.axis_status_label.clicked.connect(self.plotcanvas.on_toggle_axis)
  1325. self.ui.pref_status_label.clicked.connect(self.on_toggle_preferences)
  1326. # ###########################################################################################################
  1327. # ####################################### VARIOUS SIGNALS ###################################################
  1328. # ###########################################################################################################
  1329. # connect the abort_all_tasks related slots to the related signals
  1330. self.proc_container.idle_flag.connect(self.app_is_idle)
  1331. # signal emitted when a tab is closed in the Plot Area
  1332. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1333. # signal to close the application
  1334. self.close_app_signal.connect(self.kill_app)
  1335. # ################################# FINISHED CONNECTING SIGNALS #############################################
  1336. # ###########################################################################################################
  1337. # ###########################################################################################################
  1338. # ###########################################################################################################
  1339. self.log.debug("Finished connecting Signals.")
  1340. # ###########################################################################################################
  1341. # ##################################### Finished the CONSTRUCTOR ############################################
  1342. # ###########################################################################################################
  1343. self.log.debug("END of constructor. Releasing control.")
  1344. # ###########################################################################################################
  1345. # ########################################## SHOW GUI #######################################################
  1346. # ###########################################################################################################
  1347. # if the app is not started as headless, show it
  1348. if self.cmd_line_headless != 1:
  1349. if show_splash:
  1350. # finish the splash
  1351. self.splash.finish(self.ui)
  1352. mgui_settings = QSettings("Open Source", "FlatCAM")
  1353. if mgui_settings.contains("maximized_gui"):
  1354. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1355. if maximized_ui is True:
  1356. self.ui.showMaximized()
  1357. else:
  1358. self.ui.show()
  1359. else:
  1360. self.ui.show()
  1361. if self.defaults["global_systray_icon"]:
  1362. self.trayIcon.show()
  1363. else:
  1364. log.warning("******************* RUNNING HEADLESS *******************")
  1365. # ###########################################################################################################
  1366. # ######################################## START-UP ARGUMENTS ###############################################
  1367. # ###########################################################################################################
  1368. # test if the program was started with a script as parameter
  1369. if self.cmd_line_shellvar:
  1370. try:
  1371. cnt = 0
  1372. command_tcl = 0
  1373. for i in self.cmd_line_shellvar.split(','):
  1374. if i is not None:
  1375. # noinspection PyBroadException
  1376. try:
  1377. command_tcl = eval(i)
  1378. except Exception:
  1379. command_tcl = i
  1380. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1381. cnt += 1
  1382. # if there are Windows paths then replace the path separator with a Unix like one
  1383. if sys.platform == 'win32':
  1384. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1385. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1386. except Exception as ext:
  1387. print("ERROR: ", ext)
  1388. sys.exit(2)
  1389. if self.cmd_line_shellfile:
  1390. if self.cmd_line_headless != 1:
  1391. if self.ui.shell_dock.isHidden():
  1392. self.ui.shell_dock.show()
  1393. try:
  1394. with open(self.cmd_line_shellfile, "r") as myfile:
  1395. # if show_splash:
  1396. # self.splash.showMessage('%s: %ssec\n%s' % (
  1397. # _("Canvas initialization started.\n"
  1398. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1399. # _("Executing Tcl Script ...")),
  1400. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1401. # color=QtGui.QColor("gray"))
  1402. cmd_line_shellfile_text = myfile.read()
  1403. if self.cmd_line_headless != 1:
  1404. self.shell.exec_command(cmd_line_shellfile_text)
  1405. else:
  1406. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1407. except Exception as ext:
  1408. print("ERROR: ", ext)
  1409. sys.exit(2)
  1410. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1411. # the path/file_name must be enclosed in quotes if it contain spaces
  1412. if App.args:
  1413. self.args_at_startup.emit(App.args)
  1414. if self.defaults.old_defaults_found is True:
  1415. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1416. "Please reboot the application to update."))
  1417. self.defaults.old_defaults_found = False
  1418. # ######################################### INIT FINISHED #######################################################
  1419. # #################################################################################################################
  1420. # #################################################################################################################
  1421. # #################################################################################################################
  1422. # #################################################################################################################
  1423. # #################################################################################################################
  1424. @staticmethod
  1425. def copy_and_overwrite(from_path, to_path):
  1426. """
  1427. From here:
  1428. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1429. :param from_path: source path
  1430. :param to_path: destination path
  1431. :return: None
  1432. """
  1433. if os.path.exists(to_path):
  1434. shutil.rmtree(to_path)
  1435. try:
  1436. shutil.copytree(from_path, to_path)
  1437. except FileNotFoundError:
  1438. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\appGUI\\VisPyData\\data'
  1439. shutil.copytree(from_new_path, to_path)
  1440. def on_startup_args(self, args, silent=False):
  1441. """
  1442. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1443. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1444. :param args: a list containing the application args at startup
  1445. :return: None
  1446. """
  1447. if args is not None:
  1448. args_to_process = args
  1449. else:
  1450. args_to_process = App.args
  1451. self.log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1452. for argument in args_to_process:
  1453. if '.FlatPrj'.lower() in argument.lower():
  1454. try:
  1455. project_name = str(argument)
  1456. if project_name == "":
  1457. if silent is False:
  1458. self.inform.emit(_("Cancelled."))
  1459. else:
  1460. # self.open_project(project_name)
  1461. run_from_arg = True
  1462. # self.worker_task.emit({'fcn': self.open_project,
  1463. # 'params': [project_name, run_from_arg]})
  1464. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1465. except Exception as e:
  1466. self.log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1467. elif '.FlatConfig'.lower() in argument.lower():
  1468. try:
  1469. file_name = str(argument)
  1470. if file_name == "":
  1471. if silent is False:
  1472. self.inform.emit(_("Open Config file failed."))
  1473. else:
  1474. run_from_arg = True
  1475. # self.worker_task.emit({'fcn': self.open_config_file,
  1476. # 'params': [file_name, run_from_arg]})
  1477. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1478. except Exception as e:
  1479. self.log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1480. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1481. try:
  1482. file_name = str(argument)
  1483. if file_name == "":
  1484. if silent is False:
  1485. self.inform.emit(_("Open Script file failed."))
  1486. else:
  1487. if silent is False:
  1488. self.on_fileopenscript(name=file_name)
  1489. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1490. self.on_filerunscript(name=file_name)
  1491. except Exception as e:
  1492. self.log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1493. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1494. self.log.debug("App.on_startup_args() --> Quit event.")
  1495. sys.exit()
  1496. elif 'save'.lower() in argument.lower():
  1497. self.log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1498. self.preferencesUiManager.save_defaults()
  1499. else:
  1500. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1501. proc_arg = argument.lower()
  1502. for ext in exc_list:
  1503. proc_ext = ext.replace(' ', '')
  1504. proc_ext = '.%s' % proc_ext
  1505. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1506. file_name = str(argument)
  1507. if file_name == "":
  1508. if silent is False:
  1509. self.inform.emit(_("Open Excellon file failed."))
  1510. else:
  1511. self.on_fileopenexcellon(name=file_name, signal=None)
  1512. return
  1513. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1514. for ext in gco_list:
  1515. proc_ext = ext.replace(' ', '')
  1516. proc_ext = '.%s' % proc_ext
  1517. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1518. file_name = str(argument)
  1519. if file_name == "":
  1520. if silent is False:
  1521. self.inform.emit(_("Open GCode file failed."))
  1522. else:
  1523. self.on_fileopengcode(name=file_name, signal=None)
  1524. return
  1525. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1526. for ext in grb_list:
  1527. proc_ext = ext.replace(' ', '')
  1528. proc_ext = '.%s' % proc_ext
  1529. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1530. file_name = str(argument)
  1531. if file_name == "":
  1532. if silent is False:
  1533. self.inform.emit(_("Open Gerber file failed."))
  1534. else:
  1535. self.on_fileopengerber(name=file_name, signal=None)
  1536. return
  1537. # if it reached here without already returning then the app was registered with a file that it does not
  1538. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1539. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1540. # for arg in args_to_process:
  1541. # if 'FlatCAM.exe' in arg:
  1542. # continue
  1543. # else:
  1544. # sys.exit(2)
  1545. def tools_database_path(self):
  1546. return os.path.join(self.data_path, 'tools_db.FlatDB')
  1547. def defaults_path(self):
  1548. return os.path.join(self.data_path, 'current_defaults.FlatConfig')
  1549. def factory_defaults_path(self):
  1550. return os.path.join(self.data_path, 'factory_defaults.FlatConfig')
  1551. def recent_files_path(self):
  1552. return os.path.join(self.data_path, 'recent.json')
  1553. def recent_projects_path(self):
  1554. return os.path.join(self.data_path, 'recent_projects.json')
  1555. def preprocessors_path(self):
  1556. return os.path.join(self.data_path, 'preprocessors')
  1557. def on_app_restart(self):
  1558. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1559. # be left in the SySTray
  1560. try:
  1561. self.trayIcon.hide()
  1562. except Exception:
  1563. pass
  1564. fcTranslate.restart_program(app=self)
  1565. def clear_pool(self):
  1566. """
  1567. Clear the multiprocessing pool and calls garbage collector.
  1568. :return: None
  1569. """
  1570. self.pool.close()
  1571. self.pool = Pool()
  1572. self.pool_recreated.emit(self.pool)
  1573. gc.collect()
  1574. def install_tools(self):
  1575. """
  1576. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1577. Instantiation of the Tools classes.
  1578. The order that the tools are installed is important as they can depend on each other install position.
  1579. :return: None
  1580. """
  1581. # shell tool has t obe initialized always first because other tools print messages in the Shell Dock
  1582. self.shell = FCShell(app=self, version=self.version)
  1583. self.distance_tool = Distance(self)
  1584. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1585. before=self.ui.menueditorigin,
  1586. separator=False)
  1587. self.distance_min_tool = DistanceMin(self)
  1588. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1589. pos=self.ui.menuedit,
  1590. before=self.ui.menueditorigin,
  1591. separator=True)
  1592. self.dblsidedtool = DblSidedTool(self)
  1593. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1594. self.cal_exc_tool = ToolCalibration(self)
  1595. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1596. before=self.dblsidedtool.menuAction,
  1597. separator=False)
  1598. self.align_objects_tool = AlignObjects(self)
  1599. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1600. self.edrills_tool = ToolExtractDrills(self)
  1601. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1602. self.panelize_tool = Panelize(self)
  1603. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1604. self.film_tool = Film(self)
  1605. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1606. self.paste_tool = SolderPaste(self)
  1607. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1608. self.calculator_tool = ToolCalculator(self)
  1609. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1610. self.sub_tool = ToolSub(self)
  1611. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1612. pos=self.ui.menutool, separator=True)
  1613. self.rules_tool = RulesCheck(self)
  1614. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1615. pos=self.ui.menutool, separator=False)
  1616. self.optimal_tool = ToolOptimal(self)
  1617. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1618. pos=self.ui.menutool, separator=True)
  1619. self.move_tool = ToolMove(self)
  1620. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1621. before=self.ui.menueditorigin, separator=True)
  1622. self.cutout_tool = CutOut(self)
  1623. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1624. before=self.sub_tool.menuAction)
  1625. self.ncclear_tool = NonCopperClear(self)
  1626. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1627. before=self.sub_tool.menuAction, separator=True)
  1628. self.paint_tool = ToolPaint(self)
  1629. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1630. before=self.sub_tool.menuAction, separator=True)
  1631. self.isolation_tool = ToolIsolation(self)
  1632. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1633. before=self.sub_tool.menuAction, separator=True)
  1634. self.drilling_tool = ToolDrilling(self)
  1635. self.drilling_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), pos=self.ui.menutool,
  1636. before=self.sub_tool.menuAction, separator=True)
  1637. self.copper_thieving_tool = ToolCopperThieving(self)
  1638. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1639. pos=self.ui.menutool)
  1640. self.fiducial_tool = ToolFiducials(self)
  1641. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1642. pos=self.ui.menutool)
  1643. self.qrcode_tool = QRCode(self)
  1644. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1645. pos=self.ui.menutool)
  1646. self.punch_tool = ToolPunchGerber(self)
  1647. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1648. self.invert_tool = ToolInvertGerber(self)
  1649. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1650. self.corners_tool = ToolCorners(self)
  1651. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1652. self.etch_tool = ToolEtchCompensation(self)
  1653. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1654. self.transform_tool = ToolTransform(self)
  1655. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1656. pos=self.ui.menuoptions, separator=True)
  1657. self.properties_tool = Properties(self)
  1658. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1659. pos=self.ui.menuoptions)
  1660. self.pdf_tool = ToolPDF(self)
  1661. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1662. pos=self.ui.menufileimport,
  1663. separator=True)
  1664. self.image_tool = ToolImage(self)
  1665. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1666. pos=self.ui.menufileimport,
  1667. separator=True)
  1668. self.pcb_wizard_tool = PcbWizard(self)
  1669. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1670. pos=self.ui.menufileimport)
  1671. self.log.debug("Tools are installed.")
  1672. def remove_tools(self):
  1673. """
  1674. Will remove all the actions in the Tool menu.
  1675. :return: None
  1676. """
  1677. for act in self.ui.menutool.actions():
  1678. self.ui.menutool.removeAction(act)
  1679. def init_tools(self):
  1680. """
  1681. Initialize the Tool tab in the notebook side of the central widget.
  1682. Remove the actions in the Tools menu.
  1683. Instantiate again the FlatCAM tools (plugins).
  1684. All this is required when changing the layout: standard, compact etc.
  1685. :return: None
  1686. """
  1687. self.log.debug("init_tools()")
  1688. # delete the data currently in the Tools Tab and the Tab itself
  1689. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1690. if widget is not None:
  1691. widget.deleteLater()
  1692. self.ui.notebook.removeTab(2)
  1693. # rebuild the Tools Tab
  1694. self.ui.tool_tab = QtWidgets.QWidget()
  1695. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1696. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1697. self.ui.notebook.addTab(self.ui.tool_tab, _("Tool"))
  1698. self.ui.tool_scroll_area = VerticalScrollArea()
  1699. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1700. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1701. # first remove all of them
  1702. self.remove_tools()
  1703. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1704. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1705. '&Command Line\tS')
  1706. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1707. # third install all of them
  1708. try:
  1709. self.install_tools()
  1710. except AttributeError:
  1711. pass
  1712. self.log.debug("Tools are initialized.")
  1713. # def parse_system_fonts(self):
  1714. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1715. # 'params': []})
  1716. def connect_tools_signals_to_toolbar(self, ui):
  1717. ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1718. ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1719. ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1720. ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1721. ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1722. ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1723. ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1724. ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1725. ui.drill_btn.triggered.connect(lambda: self.drilling_tool.run(toggle=True))
  1726. ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1727. ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1728. ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1729. ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1730. ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1731. ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1732. ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1733. ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1734. ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1735. ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1736. ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1737. ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1738. ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1739. ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1740. ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1741. def connect_toolbar_signals(self, ui):
  1742. """
  1743. Reconnect the signals to the actions in the toolbar.
  1744. This has to be done each time after the FlatCAM tools are removed/installed.
  1745. :return: None
  1746. """
  1747. # Toolbar
  1748. # File Toolbar Signals
  1749. # ui.file_new_btn.triggered.connect(self.on_file_new)
  1750. ui.file_open_btn.triggered.connect(self.f_handlers.on_file_openproject)
  1751. ui.file_save_btn.triggered.connect(self.f_handlers.on_file_saveproject)
  1752. ui.file_open_gerber_btn.triggered.connect(self.f_handlers.on_fileopengerber)
  1753. ui.file_open_excellon_btn.triggered.connect(self.f_handlers.on_fileopenexcellon)
  1754. # View Toolbar Signals
  1755. ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1756. ui.replot_btn.triggered.connect(self.plot_all)
  1757. ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1758. ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1759. ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1760. # Edit Toolbar Signals
  1761. ui.editgeo_btn.triggered.connect(self.object2editor)
  1762. ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1763. ui.copy_btn.triggered.connect(self.on_copy_command)
  1764. ui.delete_btn.triggered.connect(self.on_delete)
  1765. ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1766. ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1767. ui.origin_btn.triggered.connect(self.on_set_origin)
  1768. ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1769. ui.jmp_btn.triggered.connect(self.on_jump_to)
  1770. ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1771. # Scripting Toolbar Signals
  1772. ui.shell_btn.triggered.connect(ui.toggle_shell_ui)
  1773. ui.new_script_btn.triggered.connect(self.f_handlers.on_filenewscript)
  1774. ui.open_script_btn.triggered.connect(self.f_handlers.on_fileopenscript)
  1775. ui.run_script_btn.triggered.connect(self.f_handlers.on_filerunscript)
  1776. # Tools Toolbar Signals
  1777. try:
  1778. self.connect_tools_signals_to_toolbar(ui=ui)
  1779. except Exception as err:
  1780. self.log.debug("App.connect_toolbar_signals() tools signals -> %s" % str(err))
  1781. def object2editor(self):
  1782. """
  1783. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1784. :return: None
  1785. """
  1786. self.defaults.report_usage("object2editor()")
  1787. # disable the objects menu as it may interfere with the appEditors
  1788. self.ui.menuobjects.setDisabled(True)
  1789. edited_object = self.collection.get_active()
  1790. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1791. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1792. pass
  1793. else:
  1794. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1795. return
  1796. if isinstance(edited_object, GeometryObject):
  1797. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1798. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1799. # we set the notebook to hidden
  1800. # self.ui.splitter.setSizes([0, 1])
  1801. if edited_object.multigeo is True:
  1802. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1803. if len(sel_rows) > 1:
  1804. self.inform.emit('[WARNING_NOTCL] %s' %
  1805. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1806. "is not possible.\n"
  1807. "Edit only one geometry at a time."))
  1808. if not sel_rows:
  1809. self.inform.emit('[WARNING_NOTCL] %s.' % _("No Tool Selected"))
  1810. return
  1811. # determine the tool dia of the selected tool
  1812. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1813. # now find the key in the edited_object.tools that has this tooldia
  1814. multi_tool = 1
  1815. for tool in edited_object.tools:
  1816. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1817. multi_tool = tool
  1818. break
  1819. self.log.debug("Editing MultiGeo Geometry with tool diameter: %s" % str(multi_tool))
  1820. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1821. else:
  1822. self.log.debug("Editing SingleGeo Geometry with tool diameter.")
  1823. self.geo_editor.edit_fcgeometry(edited_object)
  1824. # set call source to the Editor we go into
  1825. self.call_source = 'geo_editor'
  1826. elif isinstance(edited_object, ExcellonObject):
  1827. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1828. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1829. if self.ui.splitter.sizes()[0] == 0:
  1830. self.ui.splitter.setSizes([1, 1])
  1831. self.exc_editor.edit_fcexcellon(edited_object)
  1832. # set call source to the Editor we go into
  1833. self.call_source = 'exc_editor'
  1834. elif isinstance(edited_object, GerberObject):
  1835. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1836. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1837. if self.ui.splitter.sizes()[0] == 0:
  1838. self.ui.splitter.setSizes([1, 1])
  1839. self.grb_editor.edit_fcgerber(edited_object)
  1840. # set call source to the Editor we go into
  1841. self.call_source = 'grb_editor'
  1842. # reset the following variables so the UI is built again after edit
  1843. edited_object.ui_build = False
  1844. elif isinstance(edited_object, CNCJobObject):
  1845. if self.ui.splitter.sizes()[0] == 0:
  1846. self.ui.splitter.setSizes([1, 1])
  1847. # set call source to the Editor we go into
  1848. self.call_source = 'gcode_editor'
  1849. self.gcode_editor.edit_fcgcode(edited_object)
  1850. # make sure that we can't select another object while in Editor Mode:
  1851. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1852. self.ui.project_frame.setDisabled(True)
  1853. # delete any selection shape that might be active as they are not relevant in Editor
  1854. self.delete_selection_shape()
  1855. # hide the Tools Toolbar
  1856. tools_tb = self.ui.toolbartools
  1857. if tools_tb.isVisible():
  1858. self.old_state_of_tools_toolbar = True
  1859. tools_tb.hide()
  1860. else:
  1861. self.old_state_of_tools_toolbar = False
  1862. self.ui.plot_tab_area.setTabText(0, _("EDITOR Area"))
  1863. self.ui.plot_tab_area.protectTab(0)
  1864. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1865. self.should_we_save = True
  1866. def editor2object(self, cleanup=None):
  1867. """
  1868. Transfers the Geometry or Excellon from it's editor to the current object.
  1869. :return: None
  1870. """
  1871. self.defaults.report_usage("editor2object()")
  1872. # re-enable the objects menu that was disabled on entry in Editor mode
  1873. self.ui.menuobjects.setDisabled(False)
  1874. # do not update a geometry or excellon object unless it comes out of an editor
  1875. if self.call_source != 'app':
  1876. edited_obj = self.collection.get_active()
  1877. if cleanup is None:
  1878. msgbox = QtWidgets.QMessageBox()
  1879. msgbox.setText(_("Do you want to save the edited object?"))
  1880. msgbox.setWindowTitle(_("Close Editor"))
  1881. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1882. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1883. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1884. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1885. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1886. msgbox.setDefaultButton(bt_yes)
  1887. msgbox.exec_()
  1888. response = msgbox.clickedButton()
  1889. if response == bt_yes:
  1890. # show the Tools Toolbar
  1891. tools_tb = self.ui.toolbartools
  1892. if self.old_state_of_tools_toolbar is True:
  1893. tools_tb.show()
  1894. # clean the Tools Tab
  1895. self.ui.tool_scroll_area.takeWidget()
  1896. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1897. self.ui.notebook.setTabText(2, _("Tool"))
  1898. if edited_obj.kind == 'geometry':
  1899. obj_type = "Geometry"
  1900. self.geo_editor.update_fcgeometry(edited_obj)
  1901. # self.geo_editor.update_options(edited_obj)
  1902. # restore GUI to the Selected TAB
  1903. # Remove anything else in the appGUI
  1904. self.ui.tool_scroll_area.takeWidget()
  1905. # update the geo object options so it is including the bounding box values
  1906. try:
  1907. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1908. edited_obj.options['xmin'] = xmin
  1909. edited_obj.options['ymin'] = ymin
  1910. edited_obj.options['xmax'] = xmax
  1911. edited_obj.options['ymax'] = ymax
  1912. except AttributeError as e:
  1913. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1914. self.log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1915. edited_obj.build_ui()
  1916. edited_obj.plot()
  1917. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1918. elif edited_obj.kind == 'gerber':
  1919. obj_type = "Gerber"
  1920. self.grb_editor.update_fcgerber()
  1921. # self.grb_editor.update_options(edited_obj)
  1922. # delete the old object (the source object) if it was an empty one
  1923. try:
  1924. if len(edited_obj.solid_geometry) == 0:
  1925. old_name = edited_obj.options['name']
  1926. self.collection.delete_by_name(old_name)
  1927. except TypeError:
  1928. # if the solid_geometry is a single Polygon the len() will not work
  1929. # in any case, falling here means that we have something in the solid_geometry, even if only
  1930. # a single Polygon, therefore we pass this
  1931. pass
  1932. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1933. # restore GUI to the Selected TAB
  1934. # Remove anything else in the GUI
  1935. self.ui.properties_scroll_area.takeWidget()
  1936. elif edited_obj.kind == 'excellon':
  1937. obj_type = "Excellon"
  1938. self.exc_editor.update_fcexcellon(edited_obj)
  1939. # self.exc_editor.update_options(edited_obj)
  1940. # restore GUI to the Selected TAB
  1941. # Remove anything else in the GUI
  1942. self.ui.tool_scroll_area.takeWidget()
  1943. # delete the old object (the source object) if it was an empty one
  1944. # find if we have drills:
  1945. has_drills = None
  1946. for tt in edited_obj.tools:
  1947. if 'drills' in edited_obj.tools[tt] and edited_obj.tools[tt]['drills']:
  1948. has_drills = True
  1949. break
  1950. # find if we have slots:
  1951. has_slots = None
  1952. for tt in edited_obj.tools:
  1953. if 'slots' in edited_obj.tools[tt] and edited_obj.tools[tt]['slots']:
  1954. has_slots = True
  1955. break
  1956. if has_drills is None and has_slots is None:
  1957. old_name = edited_obj.options['name']
  1958. self.collection.delete_by_name(name=old_name)
  1959. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1960. elif edited_obj.kind == 'cncjob':
  1961. obj_type = "CNCJob"
  1962. self.gcode_editor.update_fcgcode(edited_obj)
  1963. # self.exc_editor.update_options(edited_obj)
  1964. # restore GUI to the Selected TAB
  1965. # Remove anything else in the GUI
  1966. self.ui.tool_scroll_area.takeWidget()
  1967. edited_obj.build_ui()
  1968. # close the open tab
  1969. for idx in range(self.ui.plot_tab_area.count()):
  1970. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  1971. self.ui.plot_tab_area.closeTab(idx)
  1972. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1973. else:
  1974. self.inform.emit('[WARNING_NOTCL] %s' %
  1975. _("Select a Gerber, Geometry, Excellon or CNCJob Object to update."))
  1976. return
  1977. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1978. elif response == bt_no:
  1979. # show the Tools Toolbar
  1980. tools_tb = self.ui.toolbartools
  1981. if self.old_state_of_tools_toolbar is True:
  1982. tools_tb.show()
  1983. # clean the Tools Tab
  1984. self.ui.tool_scroll_area.takeWidget()
  1985. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1986. self.ui.notebook.setTabText(2, _("Tool"))
  1987. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1988. if edited_obj.kind == 'geometry':
  1989. self.geo_editor.deactivate()
  1990. edited_obj.build_ui()
  1991. edited_obj.plot()
  1992. elif edited_obj.kind == 'gerber':
  1993. self.grb_editor.deactivate_grb_editor()
  1994. edited_obj.build_ui()
  1995. elif edited_obj.kind == 'excellon':
  1996. self.exc_editor.deactivate()
  1997. edited_obj.build_ui()
  1998. elif edited_obj.kind == 'cncjob':
  1999. self.gcode_editor.deactivate()
  2000. edited_obj.build_ui()
  2001. # close the open tab
  2002. for idx in range(self.ui.plot_tab_area.count()):
  2003. try:
  2004. if self.ui.plot_tab_area.widget(idx).objectName() == 'gcode_editor_tab':
  2005. self.ui.plot_tab_area.closeTab(idx)
  2006. except AttributeError:
  2007. continue
  2008. else:
  2009. self.inform.emit('[WARNING_NOTCL] %s' %
  2010. _("Select a Gerber, Geometry, Excellon or CNCJob Object to update."))
  2011. return
  2012. elif response == bt_cancel:
  2013. return
  2014. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  2015. # edited_obj.build_ui()
  2016. # Switch notebook to Properties page
  2017. # self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  2018. else:
  2019. # show the Tools Toolbar
  2020. tools_tb = self.ui.toolbartools
  2021. if self.old_state_of_tools_toolbar is True:
  2022. tools_tb.show()
  2023. if isinstance(edited_obj, GeometryObject):
  2024. self.geo_editor.deactivate()
  2025. elif isinstance(edited_obj, GerberObject):
  2026. self.grb_editor.deactivate_grb_editor()
  2027. elif isinstance(edited_obj, ExcellonObject):
  2028. self.exc_editor.deactivate()
  2029. else:
  2030. self.inform.emit('[WARNING_NOTCL] %s' %
  2031. _("Select a Gerber, Geometry or Excellon Object to update."))
  2032. return
  2033. # if notebook is hidden we show it
  2034. if self.ui.splitter.sizes()[0] == 0:
  2035. self.ui.splitter.setSizes([1, 1])
  2036. # restore the call_source to app
  2037. self.call_source = 'app'
  2038. # edited_obj.plot()
  2039. self.ui.plot_tab_area.setTabText(0, _("Plot Area"))
  2040. self.ui.plot_tab_area.protectTab(0)
  2041. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2042. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2043. self.ui.project_frame.setDisabled(False)
  2044. def get_last_folder(self):
  2045. """
  2046. Get the folder path from where the last file was opened.
  2047. :return: String, last opened folder path
  2048. """
  2049. return self.defaults["global_last_folder"]
  2050. def get_last_save_folder(self):
  2051. """
  2052. Get the folder path from where the last file was saved.
  2053. :return: String, last saved folder path
  2054. """
  2055. loc = self.defaults["global_last_save_folder"]
  2056. if loc is None:
  2057. loc = self.defaults["global_last_folder"]
  2058. if loc is None:
  2059. loc = os.path.dirname(__file__)
  2060. return loc
  2061. @QtCore.pyqtSlot(str)
  2062. @QtCore.pyqtSlot(str, bool)
  2063. def info(self, msg, shell_echo=True):
  2064. """
  2065. Informs the user. Normally on the status bar, optionally
  2066. also on the shell.
  2067. :param msg: Text to write.
  2068. :type msg: str
  2069. :param shell_echo: Control if to display the message msg in the Shell
  2070. :type shell_echo: bool
  2071. :return: None
  2072. """
  2073. # Type of message in brackets at the beginning of the message.
  2074. match = re.search(r"\[(.*)\](.*)", msg)
  2075. if match:
  2076. level = match.group(1)
  2077. msg_ = match.group(2)
  2078. self.ui.fcinfo.set_status(str(msg_), level=level)
  2079. if shell_echo is True:
  2080. if level.lower() == "error":
  2081. self.shell_message(msg, error=True, show=True)
  2082. elif level.lower() == "warning":
  2083. self.shell_message(msg, warning=True, show=True)
  2084. elif level.lower() == "error_notcl":
  2085. self.shell_message(msg, error=True, show=False)
  2086. elif level.lower() == "warning_notcl":
  2087. self.shell_message(msg, warning=True, show=False)
  2088. elif level.lower() == "success":
  2089. self.shell_message(msg, success=True, show=False)
  2090. elif level.lower() == "selected":
  2091. self.shell_message(msg, selected=True, show=False)
  2092. else:
  2093. self.shell_message(msg, show=False)
  2094. else:
  2095. self.ui.fcinfo.set_status(str(msg), level="info")
  2096. # make sure that if the message is to clear the infobar with a space
  2097. # is not printed over and over on the shell
  2098. if msg != '' and shell_echo is True:
  2099. self.shell_message(msg)
  2100. def info_shell(self, msg, new_line=True):
  2101. self.shell_message(msg=msg, new_line=new_line)
  2102. def save_to_file(self, content_to_save, txt_content):
  2103. """
  2104. Save something to a file.
  2105. :return: None
  2106. """
  2107. self.defaults.report_usage("save_to_file")
  2108. self.log.debug("save_to_file()")
  2109. self.date = str(datetime.today()).rpartition('.')[0]
  2110. self.date = ''.join(c for c in self.date if c not in ':-')
  2111. self.date = self.date.replace(' ', '_')
  2112. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2113. path_to_save = self.defaults["global_last_save_folder"] if \
  2114. self.defaults["global_last_save_folder"] is not None else self.data_path
  2115. try:
  2116. filename, _f = FCFileSaveDialog.get_saved_filename(
  2117. caption=_("Save to file"),
  2118. directory=path_to_save + '/file_' + self.date,
  2119. ext_filter=filter__
  2120. )
  2121. except TypeError:
  2122. filename, _f = FCFileSaveDialog.get_saved_filename(
  2123. caption=_("Save to file"),
  2124. ext_filter=filter__)
  2125. filename = str(filename)
  2126. if filename == "":
  2127. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2128. return
  2129. else:
  2130. try:
  2131. with open(filename, 'w') as f:
  2132. ___ = f.read()
  2133. except PermissionError:
  2134. self.inform.emit('[WARNING] %s' %
  2135. _("Permission denied, saving not possible.\n"
  2136. "Most likely another app is holding the file open and not accessible."))
  2137. return
  2138. except IOError:
  2139. self.log.debug('Creating a new file ...')
  2140. f = open(filename, 'w')
  2141. f.close()
  2142. except Exception:
  2143. e = sys.exc_info()[0]
  2144. App.log.error("Could not load the file.")
  2145. App.log.error(str(e))
  2146. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2147. return
  2148. # Save content
  2149. if filename.rpartition('.')[2].lower() == 'html':
  2150. file_content = content_to_save
  2151. else:
  2152. file_content = txt_content
  2153. try:
  2154. with open(filename, "w") as f:
  2155. f.write(file_content)
  2156. except Exception:
  2157. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2158. return
  2159. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2160. def register_recent(self, kind, filename):
  2161. """
  2162. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2163. dictionary.
  2164. :param kind: type of file that was opened
  2165. :param filename: the path and file name for the file that was opened
  2166. :return:
  2167. """
  2168. self.log.debug("register_recent()")
  2169. self.log.debug(" %s" % kind)
  2170. self.log.debug(" %s" % filename)
  2171. record = {'kind': str(kind), 'filename': str(filename)}
  2172. if record in self.recent:
  2173. return
  2174. if record in self.recent_projects:
  2175. return
  2176. if record['kind'] == 'project':
  2177. self.recent_projects.insert(0, record)
  2178. else:
  2179. self.recent.insert(0, record)
  2180. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2181. self.recent.pop()
  2182. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2183. self.recent_projects.pop()
  2184. try:
  2185. f = open(self.data_path + '/recent.json', 'w')
  2186. except IOError:
  2187. App.log.error("Failed to open recent items file for writing.")
  2188. self.inform.emit('[ERROR_NOTCL] %s' %
  2189. _('Failed to open recent files file for writing.'))
  2190. return
  2191. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2192. f.close()
  2193. try:
  2194. fp = open(self.data_path + '/recent_projects.json', 'w')
  2195. except IOError:
  2196. App.log.error("Failed to open recent items file for writing.")
  2197. self.inform.emit('[ERROR_NOTCL] %s' %
  2198. _('Failed to open recent projects file for writing.'))
  2199. return
  2200. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2201. fp.close()
  2202. # Re-build the recent items menu
  2203. self.setup_recent_items()
  2204. def on_about(self):
  2205. """
  2206. Displays the "about" dialog found in the Menu --> Help.
  2207. :return: None
  2208. """
  2209. self.defaults.report_usage("on_about")
  2210. version = self.version
  2211. version_date = self.version_date
  2212. beta = self.beta
  2213. class AboutDialog(QtWidgets.QDialog):
  2214. def __init__(self, app, parent=None):
  2215. QtWidgets.QDialog.__init__(self, parent)
  2216. self.app = app
  2217. # Icon and title
  2218. self.setWindowIcon(parent.app_icon)
  2219. self.setWindowTitle(_("About"))
  2220. self.resize(600, 200)
  2221. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2222. # self.setStyleSheet(
  2223. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2224. # "background-attachment: fixed"
  2225. # )
  2226. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2227. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2228. # palette = QtGui.QPalette()
  2229. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2230. # self.setPalette(palette)
  2231. logo = QtWidgets.QLabel()
  2232. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2233. title = QtWidgets.QLabel(
  2234. "<font size=8><B>FlatCAM</B></font><BR>"
  2235. "{title}<BR>"
  2236. "<BR>"
  2237. "<BR>"
  2238. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2239. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2240. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2241. "<B>{issue}</B></a><BR>".format(
  2242. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2243. devel=_("Development"),
  2244. down=_("DOWNLOAD"),
  2245. issue=_("Issue tracker"))
  2246. )
  2247. title.setOpenExternalLinks(True)
  2248. closebtn = QtWidgets.QPushButton(_("Close"))
  2249. tab_widget = QtWidgets.QTabWidget()
  2250. description_label = QtWidgets.QLabel(
  2251. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2252. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2253. version=version,
  2254. beta=('BETA' if beta else ''),
  2255. date=version_date,
  2256. arch=platform.architecture()[0])
  2257. )
  2258. description_label.setOpenExternalLinks(True)
  2259. lic_lbl_header = QtWidgets.QLabel(
  2260. '%s:<br>%s<br>' % (
  2261. _('Licensed under the MIT license'),
  2262. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2263. "http://www.opensource.org/licenses/mit-license.php</a>"
  2264. )
  2265. )
  2266. lic_lbl_header.setOpenExternalLinks(True)
  2267. lic_lbl_body = QtWidgets.QLabel(
  2268. _(
  2269. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2270. 'of this software and associated documentation files (the "Software"), to deal\n'
  2271. 'in the Software without restriction, including without limitation the rights\n'
  2272. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2273. 'copies of the Software, and to permit persons to whom the Software is\n'
  2274. 'furnished to do so, subject to the following conditions:\n\n'
  2275. 'The above copyright notice and this permission notice shall be included in\n'
  2276. 'all copies or substantial portions of the Software.\n\n'
  2277. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2278. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2279. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2280. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2281. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2282. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2283. 'THE SOFTWARE.'
  2284. )
  2285. )
  2286. attributions_label = QtWidgets.QLabel(
  2287. _(
  2288. 'Some of the icons used are from the following sources:<br>'
  2289. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2290. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2291. 'title="Flaticon">www.flaticon.com</a></div>'
  2292. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2293. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2294. '<div>Icons by <a href="https://www.flaticon.com/authors/pixel-perfect" '
  2295. 'title="Pixel perfect">Pixel perfect</a> from <a href="https://www.flaticon.com/" '
  2296. 'title="Flaticon">www.flaticon.com</a></div>'
  2297. )
  2298. )
  2299. attributions_label.setOpenExternalLinks(True)
  2300. # layouts
  2301. layout1 = QtWidgets.QVBoxLayout()
  2302. layout1_1 = QtWidgets.QHBoxLayout()
  2303. layout1_2 = QtWidgets.QHBoxLayout()
  2304. layout2 = QtWidgets.QHBoxLayout()
  2305. layout3 = QtWidgets.QHBoxLayout()
  2306. self.setLayout(layout1)
  2307. layout1.addLayout(layout1_1)
  2308. layout1.addLayout(layout1_2)
  2309. layout1.addLayout(layout2)
  2310. layout1.addLayout(layout3)
  2311. layout1_1.addStretch()
  2312. layout1_1.addWidget(description_label)
  2313. layout1_2.addWidget(tab_widget)
  2314. self.splash_tab = QtWidgets.QWidget()
  2315. self.splash_tab.setObjectName("splash_about")
  2316. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2317. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2318. tab_widget.addTab(self.splash_tab, _("Splash"))
  2319. self.programmmers_tab = QtWidgets.QWidget()
  2320. self.programmmers_tab.setObjectName("programmers_about")
  2321. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2322. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2323. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2324. self.translators_tab = QtWidgets.QWidget()
  2325. self.translators_tab.setObjectName("translators_about")
  2326. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2327. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2328. tab_widget.addTab(self.translators_tab, _("Translators"))
  2329. self.license_tab = QtWidgets.QWidget()
  2330. self.license_tab.setObjectName("license_about")
  2331. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2332. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2333. tab_widget.addTab(self.license_tab, _("License"))
  2334. self.attributions_tab = QtWidgets.QWidget()
  2335. self.attributions_tab.setObjectName("attributions_about")
  2336. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2337. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2338. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2339. self.splash_tab_layout.addWidget(logo, stretch=0)
  2340. self.splash_tab_layout.addWidget(title, stretch=1)
  2341. pal = QtGui.QPalette()
  2342. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2343. self.prog_grid_lay = QtWidgets.QGridLayout()
  2344. self.prog_grid_lay.setHorizontalSpacing(20)
  2345. self.prog_grid_lay.setColumnStretch(0, 0)
  2346. self.prog_grid_lay.setColumnStretch(2, 1)
  2347. prog_widget = QtWidgets.QWidget()
  2348. prog_widget.setLayout(self.prog_grid_lay)
  2349. prog_scroll = QtWidgets.QScrollArea()
  2350. prog_scroll.setWidget(prog_widget)
  2351. prog_scroll.setWidgetResizable(True)
  2352. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2353. prog_scroll.setPalette(pal)
  2354. self.programmmers_tab_layout.addWidget(prog_scroll)
  2355. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2356. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2357. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2358. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2359. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2360. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2361. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2362. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2363. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2364. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2365. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2366. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2367. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2368. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2369. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2370. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2371. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2372. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2373. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2374. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2375. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2376. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2377. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2378. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2379. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2380. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2381. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2382. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2383. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2384. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2385. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2386. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2387. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2388. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2389. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2390. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2391. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2392. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2393. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2394. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2395. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2396. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2397. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2398. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2399. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2400. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2401. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2402. self.translator_grid_lay = QtWidgets.QGridLayout()
  2403. self.translator_grid_lay.setColumnStretch(0, 0)
  2404. self.translator_grid_lay.setColumnStretch(1, 0)
  2405. self.translator_grid_lay.setColumnStretch(2, 1)
  2406. self.translator_grid_lay.setColumnStretch(3, 0)
  2407. # trans_widget = QtWidgets.QWidget()
  2408. # trans_widget.setLayout(self.translator_grid_lay)
  2409. # self.translators_tab_layout.addWidget(trans_widget)
  2410. # self.translators_tab_layout.addStretch()
  2411. trans_widget = QtWidgets.QWidget()
  2412. trans_widget.setLayout(self.translator_grid_lay)
  2413. trans_scroll = QtWidgets.QScrollArea()
  2414. trans_scroll.setWidget(trans_widget)
  2415. trans_scroll.setWidgetResizable(True)
  2416. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2417. trans_scroll.setPalette(pal)
  2418. self.translators_tab_layout.addWidget(trans_scroll)
  2419. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2420. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2421. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2422. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2423. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2424. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2425. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2426. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2427. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Michel Maciejewski"), 2, 1)
  2428. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2429. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<micmac589@gmail.com>"), 2, 3)
  2430. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2431. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2432. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2433. # self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2434. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2435. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Massimiliano Golfetto"), 4, 1)
  2436. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2437. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2438. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2439. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2440. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2441. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2442. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2443. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2444. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2445. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2446. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2447. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2448. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2449. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2450. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2451. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2452. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Turkish"), 9, 0)
  2453. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mehmet Kaya"), 9, 1)
  2454. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<malatyakaya480@gmail.com>"), 9, 3)
  2455. self.translator_grid_lay.setColumnStretch(0, 0)
  2456. self.translators_tab_layout.addStretch()
  2457. self.license_tab_layout.addWidget(lic_lbl_header)
  2458. self.license_tab_layout.addWidget(lic_lbl_body)
  2459. self.license_tab_layout.addStretch()
  2460. self.attributions_tab_layout.addWidget(attributions_label)
  2461. self.attributions_tab_layout.addStretch()
  2462. layout3.addStretch()
  2463. layout3.addWidget(closebtn)
  2464. closebtn.clicked.connect(self.accept)
  2465. AboutDialog(app=self, parent=self.ui).exec_()
  2466. def on_howto(self):
  2467. """
  2468. Displays the "about" dialog found in the Menu --> Help.
  2469. :return: None
  2470. """
  2471. class HowtoDialog(QtWidgets.QDialog):
  2472. def __init__(self, app, parent=None):
  2473. QtWidgets.QDialog.__init__(self, parent)
  2474. self.app = app
  2475. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2476. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2477. "<b>click</b></a>"
  2478. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>click</b></a>"
  2479. donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2480. "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>click</b></a>"
  2481. # Icon and title
  2482. self.setWindowIcon(parent.app_icon)
  2483. self.setWindowTitle('%s ...' % _("How To"))
  2484. self.resize(750, 375)
  2485. logo = QtWidgets.QLabel()
  2486. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2487. # content = QtWidgets.QLabel(
  2488. # "%s<br>"
  2489. # "%s<br><br>"
  2490. # "%s,<br>"
  2491. # "%s<br>"
  2492. # "<ul>"
  2493. # "<li> &nbsp;%s %s</li>"
  2494. # "<li> &nbsp;%s %s</li>"
  2495. # "</ul>"
  2496. # "%s %s.<br>"
  2497. # "%s"
  2498. # "<ul>"
  2499. # "<li> &nbsp;%s &#128077;</li>"
  2500. # "<li> &nbsp;%s &#128513;</li>"
  2501. # "</ul>" %
  2502. # (
  2503. # _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2504. # _("Yet it cannot evolve without <b>contributions</b>."),
  2505. # _("If you want to see this application grow and become better and better"),
  2506. # _("you can <b>contribute</b> to the development yourself by:"),
  2507. # _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2508. # new_features_link,
  2509. # _("Bug Reports by providing the steps required to reproduce the bug"),
  2510. # bugs_link,
  2511. # _("If you like or use this program you can make a donation"),
  2512. # donation_link,
  2513. # _("You don't have to make a donation %s, and it is totally optional but:") % donation_link,
  2514. # _("it will be welcomed with joy"),
  2515. # _("it will give me a reason to continue")
  2516. # )
  2517. # )
  2518. # font-weight: bold;
  2519. content = QtWidgets.QLabel(
  2520. "%s<br>"
  2521. "%s<br><br>"
  2522. "%s,<br>"
  2523. "%s<br>"
  2524. "<ul>"
  2525. "<li> &nbsp;%s %s</li>"
  2526. "<li> &nbsp;%s %s</li>"
  2527. "</ul>"
  2528. "<br><br>"
  2529. "%s <br>"
  2530. "<span style='color: blue;'>%s</span> %s %s<br>" %
  2531. (
  2532. _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2533. _("Yet it cannot evolve without <b>contributions</b>."),
  2534. _("If you want to see this application grow and become better and better"),
  2535. _("you can <b>contribute</b> to the development yourself by:"),
  2536. _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2537. new_features_link,
  2538. _("Bug Reports by providing the steps required to reproduce the bug"),
  2539. bugs_link,
  2540. _("If you like what you have seen so far ..."),
  2541. _("Donations are NOT required."), _("But they are welcomed"),
  2542. donation_link
  2543. )
  2544. )
  2545. content.setOpenExternalLinks(True)
  2546. # palette
  2547. pal = QtGui.QPalette()
  2548. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2549. # layouts
  2550. main_layout = QtWidgets.QVBoxLayout()
  2551. self.setLayout(main_layout)
  2552. tab_layout = QtWidgets.QHBoxLayout()
  2553. buttons_hlay = QtWidgets.QHBoxLayout()
  2554. main_layout.addLayout(tab_layout)
  2555. main_layout.addLayout(buttons_hlay)
  2556. tab_widget = QtWidgets.QTabWidget()
  2557. tab_layout.addWidget(tab_widget)
  2558. closebtn = QtWidgets.QPushButton(_("Close"))
  2559. buttons_hlay.addStretch()
  2560. buttons_hlay.addWidget(closebtn)
  2561. # CONTRIBUTE section
  2562. self.intro_tab = QtWidgets.QWidget()
  2563. self.intro_tab_layout = QtWidgets.QHBoxLayout(self.intro_tab)
  2564. self.intro_tab_layout.setContentsMargins(2, 2, 2, 2)
  2565. tab_widget.addTab(self.intro_tab, _("Contribute"))
  2566. self.grid_lay = QtWidgets.QGridLayout()
  2567. self.grid_lay.setHorizontalSpacing(20)
  2568. self.grid_lay.setColumnStretch(0, 0)
  2569. self.grid_lay.setColumnStretch(1, 1)
  2570. intro_wdg = QtWidgets.QWidget()
  2571. intro_wdg.setLayout(self.grid_lay)
  2572. intro_scroll_area = QtWidgets.QScrollArea()
  2573. intro_scroll_area.setWidget(intro_wdg)
  2574. intro_scroll_area.setWidgetResizable(True)
  2575. intro_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2576. intro_scroll_area.setPalette(pal)
  2577. self.grid_lay.addWidget(logo, 0, 0)
  2578. self.grid_lay.addWidget(content, 0, 1)
  2579. self.intro_tab_layout.addWidget(intro_scroll_area)
  2580. # LINKS EXCHANGE section
  2581. self.links_tab = QtWidgets.QWidget()
  2582. self.links_tab_layout = QtWidgets.QVBoxLayout(self.links_tab)
  2583. self.links_tab_layout.setContentsMargins(2, 2, 2, 2)
  2584. tab_widget.addTab(self.links_tab, _("Links Exchange"))
  2585. self.links_lay = QtWidgets.QHBoxLayout()
  2586. links_wdg = QtWidgets.QWidget()
  2587. links_wdg.setLayout(self.links_lay)
  2588. links_scroll_area = QtWidgets.QScrollArea()
  2589. links_scroll_area.setWidget(links_wdg)
  2590. links_scroll_area.setWidgetResizable(True)
  2591. links_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2592. links_scroll_area.setPalette(pal)
  2593. self.links_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2594. self.links_tab_layout.addWidget(links_scroll_area)
  2595. # HOW TO section
  2596. self.howto_tab = QtWidgets.QWidget()
  2597. self.howto_tab_layout = QtWidgets.QVBoxLayout(self.howto_tab)
  2598. self.howto_tab_layout.setContentsMargins(2, 2, 2, 2)
  2599. tab_widget.addTab(self.howto_tab, _("How To's"))
  2600. self.howto_lay = QtWidgets.QHBoxLayout()
  2601. howto_wdg = QtWidgets.QWidget()
  2602. howto_wdg.setLayout(self.howto_lay)
  2603. howto_scroll_area = QtWidgets.QScrollArea()
  2604. howto_scroll_area.setWidget(howto_wdg)
  2605. howto_scroll_area.setWidgetResizable(True)
  2606. howto_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2607. howto_scroll_area.setPalette(pal)
  2608. self.howto_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2609. self.howto_tab_layout.addWidget(howto_scroll_area)
  2610. # BUTTONS section
  2611. closebtn.clicked.connect(self.accept)
  2612. HowtoDialog(app=self, parent=self.ui).exec_()
  2613. def install_bookmarks(self, book_dict=None):
  2614. """
  2615. Install the bookmarks actions in the Help menu -> Bookmarks
  2616. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2617. :return: None
  2618. """
  2619. if book_dict is None:
  2620. self.defaults["global_bookmarks"].update(
  2621. {
  2622. '1': ['FlatCAM', "http://flatcam.org"],
  2623. '2': [_('Backup Site'), ""]
  2624. }
  2625. )
  2626. else:
  2627. self.defaults["global_bookmarks"].clear()
  2628. self.defaults["global_bookmarks"].update(book_dict)
  2629. # first try to disconnect if somehow they get connected from elsewhere
  2630. for act in self.ui.menuhelp_bookmarks.actions():
  2631. try:
  2632. act.triggered.disconnect()
  2633. except TypeError:
  2634. pass
  2635. # clear all actions except the last one who is the Bookmark manager
  2636. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2637. pass
  2638. else:
  2639. self.ui.menuhelp_bookmarks.removeAction(act)
  2640. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2641. if self.defaults["global_bookmarks"]:
  2642. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2643. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2644. # the JSON is first making the keys as strings (therefore I have to use strings too
  2645. # or do the conversion :(
  2646. # )
  2647. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2648. # the '10' entry jsut after '1' therefore ordering as strings
  2649. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2650. key=lambda x: int(x[0]))
  2651. for entry, bookmark in sorted_bookmarks:
  2652. title = bookmark[0]
  2653. weblink = bookmark[1]
  2654. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2655. act.setText(title)
  2656. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2657. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2658. if title == _('Backup Site') and weblink == "":
  2659. act.triggered.connect(self.on_backup_site)
  2660. else:
  2661. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2662. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2663. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2664. def on_bookmarks_manager(self):
  2665. """
  2666. Adds the bookmark manager in a Tab in Plot Area
  2667. :return:
  2668. """
  2669. for idx in range(self.ui.plot_tab_area.count()):
  2670. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2671. # there can be only one instance of Bookmark Manager at one time
  2672. return
  2673. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2674. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2675. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2676. # add the tab if it was closed
  2677. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2678. # delete the absolute and relative position and messages in the infobar
  2679. # self.ui.position_label.setText("")
  2680. # self.ui.rel_position_label.setText("")
  2681. # hide coordinates toolbars in the infobar while in DB
  2682. self.ui.coords_toolbar.hide()
  2683. self.ui.delta_coords_toolbar.hide()
  2684. # Switch plot_area to preferences page
  2685. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2686. def on_backup_site(self):
  2687. msgbox = QtWidgets.QMessageBox()
  2688. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2689. "1. FlatCAM.org website is down\n"
  2690. "2. Someone forked FlatCAM project and wants to point\n"
  2691. "to his own website\n\n"
  2692. "If you can't get any informations about the application\n"
  2693. "use the YouTube channel link from the Help menu."))
  2694. msgbox.setWindowTitle(_("Alternative website"))
  2695. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2696. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2697. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2698. msgbox.setDefaultButton(bt_yes)
  2699. msgbox.exec_()
  2700. # response = msgbox.clickedButton()
  2701. def final_save(self):
  2702. """
  2703. Callback for doing a preferences save to file whenever the application is about to quit.
  2704. If the project has changes, it will ask the user to save the project.
  2705. :return: None
  2706. """
  2707. if self.save_in_progress:
  2708. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2709. return
  2710. if self.should_we_save and self.collection.get_list():
  2711. msgbox = QtWidgets.QMessageBox()
  2712. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2713. "\n"
  2714. "Do you want to Save the project?"))
  2715. msgbox.setWindowTitle(_("Save changes"))
  2716. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2717. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2718. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2719. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2720. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2721. msgbox.setDefaultButton(bt_yes)
  2722. msgbox.exec_()
  2723. response = msgbox.clickedButton()
  2724. if response == bt_yes:
  2725. try:
  2726. self.trayIcon.hide()
  2727. except Exception:
  2728. pass
  2729. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2730. elif response == bt_no:
  2731. try:
  2732. self.trayIcon.hide()
  2733. except Exception:
  2734. pass
  2735. self.quit_application()
  2736. elif response == bt_cancel:
  2737. return
  2738. else:
  2739. try:
  2740. self.trayIcon.hide()
  2741. except Exception:
  2742. pass
  2743. self.quit_application()
  2744. def quit_application(self):
  2745. """
  2746. Called (as a pyslot or not) when the application is quit.
  2747. :return: None
  2748. """
  2749. # close editors before quiting the app, if they are open
  2750. if self.geo_editor.editor_active is True:
  2751. self.geo_editor.deactivate()
  2752. try:
  2753. self.geo_editor.disconnect()
  2754. except TypeError:
  2755. pass
  2756. self.log.debug("App.quit_application() --> Geo Editor deactivated.")
  2757. if self.exc_editor.editor_active is True:
  2758. self.exc_editor.deactivate()
  2759. try:
  2760. self.grb_editor.disconnect()
  2761. except TypeError:
  2762. pass
  2763. self.log.debug("App.quit_application() --> Excellon Editor deactivated.")
  2764. if self.grb_editor.editor_active is True:
  2765. self.grb_editor.deactivate_grb_editor()
  2766. try:
  2767. self.exc_editor.disconnect()
  2768. except TypeError:
  2769. pass
  2770. self.log.debug("App.quit_application() --> Gerber Editor deactivated.")
  2771. # disconnect the mouse events
  2772. if self.is_legacy:
  2773. self.plotcanvas.graph_event_disconnect(self.mm)
  2774. self.plotcanvas.graph_event_disconnect(self.mp)
  2775. self.plotcanvas.graph_event_disconnect(self.mr)
  2776. self.plotcanvas.graph_event_disconnect(self.mdc)
  2777. self.plotcanvas.graph_event_disconnect(self.kp)
  2778. else:
  2779. self.mm = self.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move_over_plot)
  2780. self.mp = self.plotcanvas.graph_event_disconnect('mouse_press', self.on_mouse_click_over_plot)
  2781. self.mr = self.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release_over_plot)
  2782. self.mdc = self.plotcanvas.graph_event_disconnect('mouse_double_click',
  2783. self.on_mouse_double_click_over_plot)
  2784. self.kp = self.plotcanvas.graph_event_disconnect('key_press', self.ui.keyPressEvent)
  2785. self.preferencesUiManager.save_defaults(silent=True)
  2786. self.log.debug("App.quit_application() --> App Defaults saved.")
  2787. if self.cmd_line_headless != 1:
  2788. # save app state to file
  2789. stgs = QSettings("Open Source", "FlatCAM")
  2790. stgs.setValue('saved_gui_state', self.ui.saveState())
  2791. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2792. stgs.setValue(
  2793. 'language',
  2794. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2795. )
  2796. stgs.setValue(
  2797. 'notebook_font_size',
  2798. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2799. )
  2800. stgs.setValue(
  2801. 'axis_font_size',
  2802. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2803. )
  2804. stgs.setValue(
  2805. 'textbox_font_size',
  2806. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2807. )
  2808. stgs.setValue(
  2809. 'hud_font_size',
  2810. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2811. )
  2812. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2813. stgs.setValue(
  2814. 'machinist',
  2815. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2816. )
  2817. # This will write the setting to the platform specific storage.
  2818. del stgs
  2819. self.log.debug("App.quit_application() --> App UI state saved.")
  2820. # try to quit the Socket opened by ArgsThread class
  2821. try:
  2822. # self.new_launch.thread_exit = True
  2823. # self.new_launch.listener.close()
  2824. self.new_launch.stop.emit()
  2825. except Exception as err:
  2826. self.log.debug("App.quit_application() --> %s" % str(err))
  2827. # try to quit the QThread that run ArgsThread class
  2828. try:
  2829. # del self.new_launch
  2830. self.listen_th.quit()
  2831. except Exception as e:
  2832. self.log.debug("App.quit_application() --> %s" % str(e))
  2833. # terminate workers
  2834. # self.workers.__del__()
  2835. self.clear_pool()
  2836. # quit app by signalling for self.kill_app() method
  2837. # self.close_app_signal.emit()
  2838. QtWidgets.qApp.quit()
  2839. sys.exit(0)
  2840. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2841. # we use the following command
  2842. # minor_v = sys.version_info.minor
  2843. # if minor_v < 8:
  2844. # # make sure that the app closes
  2845. # sys.exit(0)
  2846. # else:
  2847. # os._exit(0) # fix to work with Python 3.8
  2848. @staticmethod
  2849. def kill_app():
  2850. QtWidgets.qApp.quit()
  2851. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2852. # we use the following command
  2853. sys.exit(0)
  2854. def on_portable_checked(self, state):
  2855. """
  2856. Callback called when the checkbox in Preferences GUI is checked.
  2857. It will set the application as portable by creating the preferences and recent files in the
  2858. 'config' folder found in the FlatCAM installation folder.
  2859. :param state: boolean, the state of the checkbox when clicked/checked
  2860. :return:
  2861. """
  2862. line_no = 0
  2863. data = None
  2864. if sys.platform != 'win32':
  2865. # this won't work in Linux or MacOS
  2866. return
  2867. # test if the app was frozen and choose the path for the configuration file
  2868. if getattr(sys, "frozen", False) is True:
  2869. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2870. else:
  2871. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2872. config_file = current_data_path + '\\configuration.txt'
  2873. try:
  2874. with open(config_file, 'r') as f:
  2875. try:
  2876. data = f.readlines()
  2877. except Exception as e:
  2878. self.log.debug('App.__init__() -->%s' % str(e))
  2879. return
  2880. except FileNotFoundError:
  2881. pass
  2882. for line in data:
  2883. line = line.strip('\n')
  2884. param = str(line).rpartition('=')
  2885. if param[0] == 'portable':
  2886. break
  2887. line_no += 1
  2888. if state:
  2889. data[line_no] = 'portable=True\n'
  2890. # create the new defauults files
  2891. # create current_defaults.FlatConfig file if there is none
  2892. try:
  2893. f = open(current_data_path + '/current_defaults.FlatConfig')
  2894. f.close()
  2895. except IOError:
  2896. self.log.debug('Creating empty current_defaults.FlatConfig')
  2897. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2898. json.dump({}, f)
  2899. f.close()
  2900. # create factory_defaults.FlatConfig file if there is none
  2901. try:
  2902. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2903. f.close()
  2904. except IOError:
  2905. self.log.debug('Creating empty factory_defaults.FlatConfig')
  2906. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2907. json.dump({}, f)
  2908. f.close()
  2909. try:
  2910. f = open(current_data_path + '/recent.json')
  2911. f.close()
  2912. except IOError:
  2913. self.log.debug('Creating empty recent.json')
  2914. f = open(current_data_path + '/recent.json', 'w')
  2915. json.dump([], f)
  2916. f.close()
  2917. try:
  2918. fp = open(current_data_path + '/recent_projects.json')
  2919. fp.close()
  2920. except IOError:
  2921. self.log.debug('Creating empty recent_projects.json')
  2922. fp = open(current_data_path + '/recent_projects.json', 'w')
  2923. json.dump([], fp)
  2924. fp.close()
  2925. # save the current defaults to the new defaults file
  2926. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2927. else:
  2928. data[line_no] = 'portable=False\n'
  2929. with open(config_file, 'w') as f:
  2930. f.writelines(data)
  2931. def on_register_files(self, obj_type=None):
  2932. """
  2933. Called whenever there is a need to register file extensions with FlatCAM.
  2934. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2935. :param obj_type: the type of object to be register for.
  2936. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2937. :return: None
  2938. """
  2939. self.log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2940. new_reg_path = 'Software\\Classes\\'
  2941. # find if the current user is admin
  2942. try:
  2943. is_admin = os.getuid() == 0
  2944. except AttributeError:
  2945. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2946. if is_admin is True:
  2947. root_path = winreg.HKEY_LOCAL_MACHINE
  2948. else:
  2949. root_path = winreg.HKEY_CURRENT_USER
  2950. # create the keys
  2951. def set_reg(name, root_pth, new_reg_path_par, value):
  2952. try:
  2953. winreg.CreateKey(root_pth, new_reg_path_par)
  2954. with winreg.OpenKey(root_pth, new_reg_path_par, 0, winreg.KEY_WRITE) as registry_key:
  2955. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2956. return True
  2957. except WindowsError:
  2958. return False
  2959. # delete key in registry
  2960. def delete_reg(root_pth, reg_path, key_to_del):
  2961. key_to_del_path = reg_path + key_to_del
  2962. try:
  2963. winreg.DeleteKey(root_pth, key_to_del_path)
  2964. return True
  2965. except WindowsError:
  2966. return False
  2967. if obj_type is None or obj_type == 'excellon':
  2968. exc_list = \
  2969. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2970. exc_list = [x for x in exc_list if x != '']
  2971. # register all keys in the Preferences window
  2972. for ext in exc_list:
  2973. new_k = new_reg_path + '.%s' % ext
  2974. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2975. # and unregister those that are no longer in the Preferences windows but are in the file
  2976. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2977. if ext not in exc_list:
  2978. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2979. # now write the updated extensions to the self.defaults
  2980. # new_ext = ''
  2981. # for ext in exc_list:
  2982. # new_ext = new_ext + ext + ', '
  2983. # self.defaults["fa_excellon"] = new_ext
  2984. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2985. if obj_type is None or obj_type == 'gcode':
  2986. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2987. gco_list = [x for x in gco_list if x != '']
  2988. # register all keys in the Preferences window
  2989. for ext in gco_list:
  2990. new_k = new_reg_path + '.%s' % ext
  2991. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2992. # and unregister those that are no longer in the Preferences windows but are in the file
  2993. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2994. if ext not in gco_list:
  2995. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2996. # now write the updated extensions to the self.defaults
  2997. # new_ext = ''
  2998. # for ext in gco_list:
  2999. # new_ext = new_ext + ext + ', '
  3000. # self.defaults["fa_gcode"] = new_ext
  3001. self.inform.emit('[success] %s' %
  3002. _("Selected GCode file extensions registered with FlatCAM."))
  3003. if obj_type is None or obj_type == 'gerber':
  3004. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3005. grb_list = [x for x in grb_list if x != '']
  3006. # register all keys in the Preferences window
  3007. for ext in grb_list:
  3008. new_k = new_reg_path + '.%s' % ext
  3009. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3010. # and unregister those that are no longer in the Preferences windows but are in the file
  3011. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3012. if ext not in grb_list:
  3013. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3014. # now write the updated extensions to the self.defaults
  3015. # new_ext = ''
  3016. # for ext in grb_list:
  3017. # new_ext = new_ext + ext + ', '
  3018. # self.defaults["fa_gerber"] = new_ext
  3019. self.inform.emit('[success] %s' %
  3020. _("Selected Gerber file extensions registered with FlatCAM."))
  3021. def add_extension(self, ext_type):
  3022. """
  3023. Add a file extension to the list for a specific object
  3024. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3025. :return:
  3026. """
  3027. if ext_type == 'excellon':
  3028. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3029. if new_ext == '':
  3030. return
  3031. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3032. if new_ext in old_val:
  3033. return
  3034. old_val.append(new_ext)
  3035. old_val.sort()
  3036. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3037. if ext_type == 'gcode':
  3038. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3039. if new_ext == '':
  3040. return
  3041. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3042. if new_ext in old_val:
  3043. return
  3044. old_val.append(new_ext)
  3045. old_val.sort()
  3046. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3047. if ext_type == 'gerber':
  3048. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3049. if new_ext == '':
  3050. return
  3051. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3052. if new_ext in old_val:
  3053. return
  3054. old_val.append(new_ext)
  3055. old_val.sort()
  3056. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3057. if ext_type == 'keyword':
  3058. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3059. if new_kw == '':
  3060. return
  3061. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3062. if new_kw in old_val:
  3063. return
  3064. old_val.append(new_kw)
  3065. old_val.sort()
  3066. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3067. # update the self.myKeywords so the model is updated
  3068. self.autocomplete_kw_list = \
  3069. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3070. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3071. self.shell.command_line().set_model_data(self.myKeywords)
  3072. def del_extension(self, ext_type):
  3073. """
  3074. Remove a file extension from the list for a specific object
  3075. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3076. :return:
  3077. """
  3078. if ext_type == 'excellon':
  3079. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3080. if new_ext == '':
  3081. return
  3082. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3083. if new_ext not in old_val:
  3084. return
  3085. old_val.remove(new_ext)
  3086. old_val.sort()
  3087. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3088. if ext_type == 'gcode':
  3089. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3090. if new_ext == '':
  3091. return
  3092. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3093. if new_ext not in old_val:
  3094. return
  3095. old_val.remove(new_ext)
  3096. old_val.sort()
  3097. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3098. if ext_type == 'gerber':
  3099. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3100. if new_ext == '':
  3101. return
  3102. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3103. if new_ext not in old_val:
  3104. return
  3105. old_val.remove(new_ext)
  3106. old_val.sort()
  3107. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3108. if ext_type == 'keyword':
  3109. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3110. if new_kw == '':
  3111. return
  3112. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3113. if new_kw not in old_val:
  3114. return
  3115. old_val.remove(new_kw)
  3116. old_val.sort()
  3117. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3118. # update the self.myKeywords so the model is updated
  3119. self.autocomplete_kw_list = \
  3120. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3121. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3122. self.shell.command_line().set_model_data(self.myKeywords)
  3123. def restore_extensions(self, ext_type):
  3124. """
  3125. Restore all file extensions associations with FlatCAM, for a specific object
  3126. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3127. :return:
  3128. """
  3129. if ext_type == 'excellon':
  3130. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3131. # for the ability to open Excellon files with .txt extension
  3132. new_exc_list = deepcopy(self.exc_list)
  3133. try:
  3134. new_exc_list.remove('txt')
  3135. except ValueError:
  3136. pass
  3137. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3138. if ext_type == 'gcode':
  3139. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3140. if ext_type == 'gerber':
  3141. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3142. if ext_type == 'keyword':
  3143. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3144. # update the self.myKeywords so the model is updated
  3145. self.autocomplete_kw_list = self.default_keywords
  3146. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3147. self.shell.commnad_line().set_model_data(self.myKeywords)
  3148. def delete_all_extensions(self, ext_type):
  3149. """
  3150. Delete all file extensions associations with FlatCAM, for a specific object
  3151. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3152. :return:
  3153. """
  3154. if ext_type == 'excellon':
  3155. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3156. if ext_type == 'gcode':
  3157. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3158. if ext_type == 'gerber':
  3159. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3160. if ext_type == 'keyword':
  3161. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3162. # update the self.myKeywords so the model is updated
  3163. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3164. self.shell.command_line().set_model_data(self.myKeywords)
  3165. def on_edit_join(self, name=None):
  3166. """
  3167. Callback for Edit->Join. Joins the selected geometry objects into
  3168. a new one.
  3169. :return: None
  3170. """
  3171. self.defaults.report_usage("on_edit_join()")
  3172. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3173. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3174. geo_type_set = set()
  3175. objs = self.collection.get_selected()
  3176. if len(objs) < 2:
  3177. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3178. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3179. return 'fail'
  3180. for obj in objs:
  3181. geo_type_set.add(obj.multigeo)
  3182. # if len(geo_type_list) == 1 means that all list elements are the same
  3183. if len(geo_type_set) != 1:
  3184. self.inform.emit('[ERROR] %s' %
  3185. _("Failed join. The Geometry objects are of different types.\n"
  3186. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3187. "convert from one to another and retry joining \n"
  3188. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3189. "the result may not be what was expected. \n"
  3190. "Check the generated GCODE."))
  3191. return
  3192. fuse_tools = self.defaults["geometry_merge_fuse_tools"]
  3193. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3194. if True in geo_type_set:
  3195. def initialize(geo_obj, app):
  3196. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True, fuse_tools=fuse_tools)
  3197. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3198. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3199. for v in geo_obj.tools.values():
  3200. v['data']['name'] = obj_name_multi
  3201. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3202. else:
  3203. def initialize(geo_obj, app):
  3204. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False, fuse_tools=fuse_tools)
  3205. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3206. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3207. for v in geo_obj.tools.values():
  3208. v['data']['name'] = obj_name_single
  3209. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3210. self.should_we_save = True
  3211. def on_edit_join_exc(self):
  3212. """
  3213. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3214. a new Excellon.
  3215. :return: None
  3216. """
  3217. self.defaults.report_usage("on_edit_join_exc()")
  3218. objs = self.collection.get_selected()
  3219. for obj in objs:
  3220. if not isinstance(obj, ExcellonObject):
  3221. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3222. return
  3223. if len(objs) < 2:
  3224. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3225. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3226. return 'fail'
  3227. fuse_tools = self.defaults["excellon_merge_fuse_tools"]
  3228. def initialize(exc_obj, app):
  3229. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals, fuse_tools=fuse_tools)
  3230. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3231. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3232. self.should_we_save = True
  3233. def on_edit_join_grb(self):
  3234. """
  3235. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3236. a new Gerber object.
  3237. :return: None
  3238. """
  3239. self.defaults.report_usage("on_edit_join_grb()")
  3240. objs = self.collection.get_selected()
  3241. for obj in objs:
  3242. if not isinstance(obj, GerberObject):
  3243. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3244. return
  3245. if len(objs) < 2:
  3246. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3247. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3248. return 'fail'
  3249. def initialize(grb_obj, app):
  3250. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3251. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3252. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3253. self.should_we_save = True
  3254. def on_convert_singlegeo_to_multigeo(self):
  3255. """
  3256. Called for converting a Geometry object from single-geo to multi-geo.
  3257. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3258. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3259. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3260. the solid-geometry of that tool.
  3261. :return: None
  3262. """
  3263. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3264. obj = self.collection.get_active()
  3265. if obj is None:
  3266. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3267. return
  3268. if not isinstance(obj, GeometryObject):
  3269. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3270. return
  3271. obj.multigeo = True
  3272. for tooluid, dict_value in obj.tools.items():
  3273. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3274. if not isinstance(obj.solid_geometry, list):
  3275. obj.solid_geometry = [obj.solid_geometry]
  3276. # obj.solid_geometry[:] = []
  3277. obj.plot()
  3278. self.should_we_save = True
  3279. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3280. def on_convert_multigeo_to_singlegeo(self):
  3281. """
  3282. Called for converting a Geometry object from multi-geo to single-geo.
  3283. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3284. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3285. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3286. the solid-geometry of that tool.
  3287. :return: None
  3288. """
  3289. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3290. obj = self.collection.get_active()
  3291. if obj is None:
  3292. self.inform.emit('[ERROR_NOTCL] %s' %
  3293. _("Failed. Select a Geometry Object and try again."))
  3294. return
  3295. if not isinstance(obj, GeometryObject):
  3296. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3297. (_("Expected a GeometryObject, got"), type(obj)))
  3298. return
  3299. obj.multigeo = False
  3300. total_solid_geometry = []
  3301. for tooluid, dict_value in obj.tools.items():
  3302. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3303. # clear the original geometry
  3304. dict_value['solid_geometry'][:] = []
  3305. obj.solid_geometry = deepcopy(total_solid_geometry)
  3306. obj.plot()
  3307. self.should_we_save = True
  3308. self.inform.emit('[success] %s' %
  3309. _("A Geometry object was converted to SingleGeo type."))
  3310. def on_defaults_dict_change(self, field):
  3311. """
  3312. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3313. Edit -> Preferences tab window.
  3314. :param field: the key of the self.defaults dictionary that was changed.
  3315. :return: None
  3316. """
  3317. self.preferencesUiManager.defaults_write_form_field(field=field)
  3318. if field == "units":
  3319. self.set_screen_units(self.defaults['units'])
  3320. def set_screen_units(self, units):
  3321. """
  3322. Set the FlatCAM units on the status bar.
  3323. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3324. :return: None
  3325. """
  3326. self.ui.units_label.setText("[" + units.lower() + "]")
  3327. def on_toggle_units_click(self):
  3328. try:
  3329. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3330. except (TypeError, AttributeError):
  3331. pass
  3332. if self.defaults["units"] == 'MM':
  3333. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3334. else:
  3335. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3336. self.on_toggle_units(no_pref=True)
  3337. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3338. lambda: self.on_toggle_units(no_pref=False))
  3339. def scale_defaults(self, sfactor, dimensions):
  3340. for dim in dimensions:
  3341. if dim in ['geometry_cnctooldia', 'tools_ncc_tools', 'tools_solderpaste_tools', 'tools_iso_tooldia',
  3342. 'tools_paint_tooldia', 'tools_transform_ref_point', 'tools_cal_toolchange_xy',
  3343. 'gerber_editor_newdim', 'tools_drill_toolchangexy', 'tools_drill_endxy',
  3344. 'geometry_toolchangexy', 'geometry_endxy', 'tools_solderpaste_xy_toolchange']:
  3345. if not self.defaults[dim] or self.defaults[dim] == '':
  3346. continue
  3347. if isinstance(self.defaults[dim], str):
  3348. try:
  3349. tools_diameters = eval(self.defaults[dim])
  3350. except Exception as e:
  3351. self.log.debug("App.on_toggle_units().scale_defaults() lists --> %s" % str(e))
  3352. continue
  3353. elif isinstance(self.defaults[dim], (float, int)):
  3354. tools_diameters = [self.defaults[dim]]
  3355. else:
  3356. tools_diameters = list(self.defaults[dim])
  3357. if isinstance(tools_diameters, (tuple, list)):
  3358. pass
  3359. elif isinstance(tools_diameters, (int, float)):
  3360. tools_diameters = [self.defaults[dim]]
  3361. else:
  3362. continue
  3363. td_len = len(tools_diameters)
  3364. conv_list = []
  3365. for t in range(td_len):
  3366. conv_list.append(self.dec_format(float(tools_diameters[t]) * sfactor, self.decimals))
  3367. self.defaults[dim] = conv_list
  3368. elif dim in ['global_gridx', 'global_gridy']:
  3369. # format the number of decimals to the one specified in self.decimals
  3370. try:
  3371. val = float(self.defaults[dim]) * sfactor
  3372. except Exception as e:
  3373. self.log.debug('App.on_toggle_units().scale_defaults() grids --> %s' % str(e))
  3374. continue
  3375. self.defaults[dim] = self.dec_format(val, self.decimals)
  3376. else:
  3377. # the number of decimals for the rest is kept unchanged
  3378. if self.defaults[dim]:
  3379. try:
  3380. val = float(self.defaults[dim]) * sfactor
  3381. except Exception as e:
  3382. self.log.debug(
  3383. 'App.on_toggle_units().scale_defaults() standard --> Value: %s %s' % (str(dim), str(e))
  3384. )
  3385. continue
  3386. self.defaults[dim] = self.dec_format(val, self.decimals)
  3387. def on_toggle_units(self, no_pref=False):
  3388. """
  3389. Callback for the Units radio-button change in the Preferences tab.
  3390. Changes the application's default units adn for the project too.
  3391. If changing the project's units, the change propagates to all of
  3392. the objects in the project.
  3393. :return: None
  3394. """
  3395. self.defaults.report_usage("on_toggle_units")
  3396. if self.toggle_units_ignore:
  3397. return
  3398. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3399. # If option is the same, then ignore
  3400. if new_units == self.defaults["units"].upper():
  3401. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3402. return
  3403. # Keys in self.defaults for which to scale their values
  3404. dimensions = [
  3405. # Global
  3406. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3407. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin',
  3408. # Gerber Object
  3409. 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3410. # Gerber Editor
  3411. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3412. "gerber_editor_newdim", "gerber_editor_ma_low", "gerber_editor_ma_high",
  3413. # Excellon Object
  3414. "excellon_milling_dia", 'excellon_tooldia', 'excellon_slot_tooldia',
  3415. # Excellon Editor
  3416. "excellon_editor_newdia", "excellon_editor_lin_pitch", "excellon_editor_slot_lin_pitch",
  3417. "excellon_editor_slot_length",
  3418. # Geometry Object
  3419. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3420. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3421. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3422. "geometry_extracut_length", "geometry_z_pdepth",
  3423. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy", "geometry_area_overz",
  3424. # CNCJob Object
  3425. 'cncjob_tooldia', "cncjob_al_travelz", "cncjob_al_probe_depth", "cncjob_al_grbl_jog_step",
  3426. "cncjob_al_grbl_jog_fr", "cncjob_al_grbl_travelz",
  3427. # Isolation Tool
  3428. "tools_iso_tool_vtipdia", 'tools_iso_tooldia', "tools_iso_tool_cutz",
  3429. # Drilling Tool
  3430. 'tools_drill_cutz', 'tools_drill_depthperpass', 'tools_drill_travelz', 'tools_drill_endz',
  3431. 'tools_drill_endxy', 'tools_drill_feedrate_z', 'tools_drill_toolchangez', "tools_drill_drill_overlap",
  3432. 'tools_drill_offset', "tools_drill_toolchangexy", "tools_drill_startz", 'tools_drill_feedrate_rapid',
  3433. "tools_drill_feedrate_probe", "tools_drill_z_pdepth", "tools_drill_area_overz",
  3434. # NCC Tool
  3435. "tools_ncc_tools", "tools_ncc_margin", "tools_ncc_offset_value", "tools_ncc_cutz", "tools_ncc_tipdia",
  3436. "tools_ncc_newdia",
  3437. # Cutout Tool
  3438. "tools_cutout_tooldia", 'tools_cutout_margin', "tools_cutout_z", "tools_cutout_depthperpass",
  3439. 'tools_cutout_gapsize', 'tools_cutout_gap_depth', 'tools_cutout_mb_dia', 'tools_cutout_mb_spacing',
  3440. # Paint Tool
  3441. "tools_paint_tooldia", 'tools_paint_offset', "tools_paint_cutz", "tools_paint_tipdia", "tools_paint_newdia",
  3442. # 2Sided Tool
  3443. "tools_2sided_drilldia",
  3444. # Film Tool
  3445. "tools_film_boundary", "tools_film_scale_stroke",
  3446. # Panel Tool
  3447. "tools_panelize_spacing_columns", "tools_panelize_spacing_rows", "tools_panelize_constrainx",
  3448. "tools_panelize_constrainy",
  3449. # Calculators Tool
  3450. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3451. # Transform Tool
  3452. "tools_transform_ref_point", "tools_transform_offset_x", "tools_transform_offset_y",
  3453. "tools_transform_buffer_dis",
  3454. # SolderPaste Tool
  3455. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3456. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3457. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3458. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3459. # Corner Markers Tool
  3460. "tools_corners_thickness", "tools_corners_length", "tools_corners_margin",
  3461. # Check Rules Tool
  3462. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val", "tools_cr_s2sm_val",
  3463. "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val", "tools_cr_h2h_val", "tools_cr_dh_val",
  3464. # QRCode Tool
  3465. "tools_qrcode_border_size",
  3466. # Copper Thieving Tool
  3467. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3468. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3469. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3470. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3471. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3472. "tools_copper_thieving_mask_clearance",
  3473. # Fiducials Tool
  3474. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3475. # Calibration Tool
  3476. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3477. # Drills Extraction Tool
  3478. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3479. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3480. # Punch Gerber Tool
  3481. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3482. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3483. # Invert Gerber Tool
  3484. "tools_invert_margin",
  3485. ]
  3486. # The scaling factor depending on choice of units.
  3487. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3488. # Changing project units. Warn user.
  3489. msgbox = QtWidgets.QMessageBox()
  3490. msgbox.setWindowTitle(_("Toggle Units"))
  3491. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3492. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3493. msgbox.setText(_("Changing the units of the project\n"
  3494. "will scale all objects.\n\n"
  3495. "Do you want to continue?"))
  3496. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3497. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3498. msgbox.setDefaultButton(bt_ok)
  3499. msgbox.exec_()
  3500. response = msgbox.clickedButton()
  3501. if response == bt_ok:
  3502. if no_pref is False:
  3503. self.preferencesUiManager.defaults_read_form()
  3504. self.scale_defaults(factor, dimensions)
  3505. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3506. self.defaults["units"] = new_units
  3507. # update the defaults from form, some may assume that the conversion is enough and it's not
  3508. self.on_options_app2project()
  3509. # update the objects
  3510. for obj in self.collection.get_list():
  3511. obj.convert_units(new_units)
  3512. # make that the properties stored in the object are also updated
  3513. self.app_obj.object_changed.emit(obj)
  3514. # rebuild the object UI
  3515. obj.build_ui()
  3516. # change this only if the workspace is active
  3517. if self.defaults['global_workspace'] is True:
  3518. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3519. # adjust the grid values on the main toolbar
  3520. val_x = float(self.defaults['global_gridx']) * factor
  3521. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3522. current = self.collection.get_active()
  3523. if current is not None:
  3524. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3525. if not isinstance(current, GeometryObject):
  3526. current.to_form()
  3527. # replot all objects
  3528. self.plot_all()
  3529. # set the status labels to reflect the current FlatCAM units
  3530. self.set_screen_units(new_units)
  3531. # signal to the app that we changed the object properties and it should save the project
  3532. self.should_we_save = True
  3533. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3534. else:
  3535. # Undo toggling
  3536. self.toggle_units_ignore = True
  3537. if self.defaults['units'].upper() == 'MM':
  3538. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3539. else:
  3540. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3541. self.toggle_units_ignore = False
  3542. # store the grid values so they are not changed in the next step
  3543. val_x = float(self.defaults['global_gridx'])
  3544. val_y = float(self.defaults['global_gridy'])
  3545. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3546. self.preferencesUiManager.defaults_read_form()
  3547. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3548. # in self.defaults from the GUI elements but
  3549. # I don't want it for the grid values, so I update them here
  3550. self.defaults['global_gridx'] = val_x
  3551. self.defaults['global_gridy'] = val_y
  3552. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3553. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3554. def on_deselect_all(self):
  3555. self.collection.set_all_inactive()
  3556. self.delete_selection_shape()
  3557. def on_workspace_modified(self):
  3558. # self.save_defaults(silent=True)
  3559. self.plotcanvas.delete_workspace()
  3560. self.preferencesUiManager.defaults_read_form()
  3561. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3562. def on_workspace(self):
  3563. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3564. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3565. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3566. else:
  3567. self.plotcanvas.delete_workspace()
  3568. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3569. self.preferencesUiManager.defaults_read_form()
  3570. # self.save_defaults(silent=True)
  3571. def on_workspace_toggle(self):
  3572. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3573. try:
  3574. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3575. except TypeError:
  3576. pass
  3577. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3578. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3579. self.on_workspace()
  3580. def on_cursor_type(self, val):
  3581. """
  3582. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3583. :return: None
  3584. """
  3585. self.app_cursor.enabled = False
  3586. if val == 'small':
  3587. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3588. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3589. self.app_cursor = self.plotcanvas.new_cursor()
  3590. else:
  3591. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3592. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3593. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3594. if self.ui.grid_snap_btn.isChecked():
  3595. self.app_cursor.enabled = True
  3596. else:
  3597. self.app_cursor.enabled = False
  3598. def on_tool_add_keypress(self):
  3599. # ## Current application units in Upper Case
  3600. self.units = self.defaults['units'].upper()
  3601. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3602. # work only if the notebook tab on focus is the properties_tab and only if the object is Geometry
  3603. if notebook_widget_name == 'properties_tab':
  3604. if self.collection.get_active().kind == 'geometry':
  3605. # Tool add works for Geometry only if Advanced is True in Preferences
  3606. if self.defaults["global_app_level"] == 'a':
  3607. tool_add_popup = FCInputSpinner(title='%s...' % _("New Tool"),
  3608. text='%s:' % _('Enter a Tool Diameter'),
  3609. min=0.0000, max=100.0000, decimals=self.decimals, step=0.1)
  3610. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3611. tool_add_popup.wdg.selectAll()
  3612. val, ok = tool_add_popup.get_value()
  3613. if ok:
  3614. if float(val) == 0:
  3615. self.inform.emit('[WARNING_NOTCL] %s' %
  3616. _("Please enter a tool diameter with non-zero value, in Float format."))
  3617. return
  3618. self.collection.get_active().on_tool_add(clicked_state=False, dia=float(val))
  3619. else:
  3620. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3621. else:
  3622. msgbox = QtWidgets.QMessageBox()
  3623. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3624. "Go to Preferences -> General - Show Advanced Options."))
  3625. msgbox.setWindowTitle("Tool adding ...")
  3626. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3627. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3628. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3629. msgbox.setDefaultButton(bt_ok)
  3630. msgbox.exec_()
  3631. # work only if the notebook tab on focus is the Tools_Tab
  3632. if notebook_widget_name == 'tool_tab':
  3633. try:
  3634. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3635. except AttributeError:
  3636. return
  3637. # and only if the tool is NCC Tool
  3638. if tool_widget == self.ncclear_tool.toolName:
  3639. self.ncclear_tool.on_add_tool_by_key()
  3640. # and only if the tool is Paint Area Tool
  3641. elif tool_widget == self.paint_tool.toolName:
  3642. self.paint_tool.on_add_tool_by_key()
  3643. # and only if the tool is Solder Paste Dispensing Tool
  3644. elif tool_widget == self.paste_tool.toolName:
  3645. self.paste_tool.on_add_tool_by_key()
  3646. # and only if the tool is Isolation Tool
  3647. elif tool_widget == self.isolation_tool.toolName:
  3648. self.isolation_tool.on_add_tool_by_key()
  3649. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3650. # See description below.
  3651. def on_delete_keypress(self):
  3652. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3653. # work only if the notebook tab on focus is the properties_tab and only if the object is Geometry
  3654. if notebook_widget_name == 'properties_tab':
  3655. if self.collection.get_active().kind == 'geometry':
  3656. self.collection.get_active().on_tool_delete()
  3657. # work only if the notebook tab on focus is the Tools_Tab
  3658. elif notebook_widget_name == 'tool_tab':
  3659. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3660. # and only if the tool is NCC Tool
  3661. if tool_widget == self.ncclear_tool.toolName:
  3662. self.ncclear_tool.on_tool_delete()
  3663. # and only if the tool is Paint Tool
  3664. elif tool_widget == self.paint_tool.toolName:
  3665. self.paint_tool.on_tool_delete()
  3666. # and only if the tool is Solder Paste Dispensing Tool
  3667. elif tool_widget == self.paste_tool.toolName:
  3668. self.paste_tool.on_tool_delete()
  3669. # and only if the tool is Isolation Tool
  3670. elif tool_widget == self.isolation_tool.toolName:
  3671. self.isolation_tool.on_tool_delete()
  3672. else:
  3673. self.on_delete()
  3674. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3675. # some screens you have to be careful where you hover with your mouse.
  3676. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3677. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3678. # Complicated, I know :)
  3679. def on_delete(self, force_deletion=False):
  3680. """
  3681. Delete the currently selected FlatCAMObjs.
  3682. :param force_deletion: used by Tcl command
  3683. :return: None
  3684. """
  3685. self.defaults.report_usage("on_delete()")
  3686. response = None
  3687. bt_ok = None
  3688. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3689. # a geometry object before we update it.
  3690. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3691. and self.grb_editor.editor_active is False and self.gcode_editor.editor_active is False:
  3692. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3693. msgbox = QtWidgets.QMessageBox()
  3694. msgbox.setWindowTitle(_("Delete objects"))
  3695. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3696. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3697. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3698. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3699. "the selected objects?"))
  3700. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3701. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3702. msgbox.setDefaultButton(bt_ok)
  3703. msgbox.exec_()
  3704. response = msgbox.clickedButton()
  3705. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3706. response = bt_ok
  3707. if response == bt_ok:
  3708. if self.collection.get_active():
  3709. self.log.debug("App.on_delete()")
  3710. for obj_active in self.collection.get_selected():
  3711. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3712. if obj_active.kind == 'gerber':
  3713. obj_active.mark_shapes_storage.clear()
  3714. obj_active.mark_shapes.clear(update=True)
  3715. obj_active.mark_shapes.enabled = False
  3716. elif obj_active.kind == 'cncjob':
  3717. try:
  3718. obj_active.text_col.enabled = False
  3719. del obj_active.text_col
  3720. obj_active.annotation.clear(update=True)
  3721. del obj_active.annotation
  3722. obj_active.probing_shapes.clear(update=True)
  3723. except AttributeError as e:
  3724. self.log.debug(
  3725. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3726. )
  3727. while self.collection.get_selected():
  3728. self.delete_first_selected()
  3729. # make sure that the selection shape is deleted, too
  3730. self.delete_selection_shape()
  3731. # if there are no longer objects delete also the exclusion areas shapes
  3732. if not self.collection.get_list():
  3733. self.exc_areas.clear_shapes()
  3734. self.inform.emit('%s...' % _("Object(s) deleted"))
  3735. else:
  3736. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3737. else:
  3738. self.inform.emit(_("Save the work in Editor and try again ..."))
  3739. def delete_first_selected(self):
  3740. # Keep this for later
  3741. try:
  3742. sel_obj = self.collection.get_active()
  3743. name = sel_obj.options["name"]
  3744. isPlotted = sel_obj.options["plot"]
  3745. except AttributeError:
  3746. self.log.debug("Nothing selected for deletion")
  3747. return
  3748. if self.is_legacy is True:
  3749. # Remove plot only if the object was plotted otherwise delaxes will fail
  3750. if isPlotted:
  3751. try:
  3752. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3753. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3754. except Exception as e:
  3755. self.log.debug("App.delete_first_selected() --> %s" % str(e))
  3756. self.plotcanvas.auto_adjust_axes()
  3757. # Remove from dictionary
  3758. self.collection.delete_active()
  3759. # Clear form
  3760. self.setup_default_properties_tab()
  3761. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3762. def on_set_origin(self):
  3763. """
  3764. Set the origin to the left mouse click position
  3765. :return: None
  3766. """
  3767. # display the message for the user
  3768. # and ask him to click on the desired position
  3769. self.defaults.report_usage("on_set_origin()")
  3770. def origin_replot():
  3771. def worker_task():
  3772. with self.proc_container.new('%s...' % _("Plotting")):
  3773. for obj in self.collection.get_list():
  3774. obj.plot()
  3775. self.plotcanvas.fit_view()
  3776. if self.is_legacy:
  3777. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3778. else:
  3779. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3780. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3781. self.inform.emit(_('Click to set the origin ...'))
  3782. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3783. # first disconnect it as it may have been used by something else
  3784. try:
  3785. self.replot_signal.disconnect()
  3786. except TypeError:
  3787. pass
  3788. self.replot_signal[list].connect(origin_replot)
  3789. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3790. """
  3791. :param event:
  3792. :param location:
  3793. :param noplot:
  3794. :param use_thread:
  3795. :return:
  3796. """
  3797. noplot_sig = noplot
  3798. def worker_task():
  3799. with self.proc_container.new(_("Setting Origin...")):
  3800. obj_list = self.collection.get_list()
  3801. for obj in obj_list:
  3802. obj.offset((x, y))
  3803. self.app_obj.object_changed.emit(obj)
  3804. # Update the object bounding box options
  3805. a, b, c, d = obj.bounds()
  3806. obj.options['xmin'] = a
  3807. obj.options['ymin'] = b
  3808. obj.options['xmax'] = c
  3809. obj.options['ymax'] = d
  3810. self.inform.emit('[success] %s...' % _('Origin set'))
  3811. for obj in obj_list:
  3812. out_name = obj.options["name"]
  3813. if obj.kind == 'gerber':
  3814. obj.source_file = self.f_handlers.export_gerber(
  3815. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3816. elif obj.kind == 'excellon':
  3817. obj.source_file = self.f_handlers.export_excellon(
  3818. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3819. if noplot_sig is False:
  3820. self.replot_signal.emit([])
  3821. if location is not None:
  3822. if len(location) != 2:
  3823. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3824. return 'fail'
  3825. x, y = location
  3826. if use_thread is True:
  3827. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3828. else:
  3829. worker_task()
  3830. self.should_we_save = True
  3831. return
  3832. if event is not None and event.button == 1:
  3833. if self.is_legacy is False:
  3834. event_pos = event.pos
  3835. else:
  3836. event_pos = (event.xdata, event.ydata)
  3837. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3838. if self.grid_status():
  3839. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3840. else:
  3841. pos = pos_canvas
  3842. x = 0 - pos[0]
  3843. y = 0 - pos[1]
  3844. if use_thread is True:
  3845. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3846. else:
  3847. worker_task()
  3848. self.should_we_save = True
  3849. def on_move2origin(self, use_thread=True):
  3850. """
  3851. Move selected objects to origin.
  3852. :param use_thread: Control if to use threaded operation. Boolean.
  3853. :return:
  3854. """
  3855. def worker_task():
  3856. with self.proc_container.new(_("Moving to Origin...")):
  3857. obj_list = self.collection.get_selected()
  3858. if not obj_list:
  3859. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3860. return
  3861. xminlist = []
  3862. yminlist = []
  3863. # first get a bounding box to fit all
  3864. for obj in obj_list:
  3865. xmin, ymin, xmax, ymax = obj.bounds()
  3866. xminlist.append(xmin)
  3867. yminlist.append(ymin)
  3868. # get the minimum x,y for all objects selected
  3869. x = min(xminlist)
  3870. y = min(yminlist)
  3871. for obj in obj_list:
  3872. obj.offset((-x, -y))
  3873. self.app_obj.object_changed.emit(obj)
  3874. # Update the object bounding box options
  3875. a, b, c, d = obj.bounds()
  3876. obj.options['xmin'] = a
  3877. obj.options['ymin'] = b
  3878. obj.options['xmax'] = c
  3879. obj.options['ymax'] = d
  3880. for obj in obj_list:
  3881. obj.plot()
  3882. for obj in obj_list:
  3883. out_name = obj.options["name"]
  3884. if obj.kind == 'gerber':
  3885. obj.source_file = self.f_handlers.export_gerber(
  3886. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3887. elif obj.kind == 'excellon':
  3888. obj.source_file = self.f_handlers.export_excellon(
  3889. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3890. self.inform.emit('[success] %s...' % _('Origin set'))
  3891. if use_thread is True:
  3892. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3893. else:
  3894. worker_task()
  3895. self.should_we_save = True
  3896. def on_jump_to(self, custom_location=None, fit_center=True):
  3897. """
  3898. Jump to a location by setting the mouse cursor location.
  3899. :param custom_location: Jump to a specified point. (x, y) tuple.
  3900. :param fit_center: If to fit view. Boolean.
  3901. :return:
  3902. """
  3903. self.defaults.report_usage("on_jump_to()")
  3904. if not custom_location:
  3905. dia_box_location = None
  3906. try:
  3907. dia_box_location = eval(self.clipboard.text())
  3908. except Exception:
  3909. pass
  3910. if type(dia_box_location) == tuple:
  3911. dia_box_location = str(dia_box_location)
  3912. else:
  3913. dia_box_location = None
  3914. # dia_box = Dialog_box(title=_("Jump to ..."),
  3915. # label=_("Enter the coordinates in format X,Y:"),
  3916. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3917. # initial_text=dia_box_location)
  3918. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3919. label=_("Enter the coordinates in format X,Y:"),
  3920. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3921. initial_text=dia_box_location,
  3922. reference=self.defaults['global_jump_ref'])
  3923. if dia_box.ok is True:
  3924. try:
  3925. location = eval(dia_box.location)
  3926. if not isinstance(location, tuple):
  3927. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3928. return
  3929. if dia_box.reference == 'rel':
  3930. rel_x = self.mouse[0] + location[0]
  3931. rel_y = self.mouse[1] + location[1]
  3932. location = (rel_x, rel_y)
  3933. self.defaults['global_jump_ref'] = dia_box.reference
  3934. except Exception:
  3935. return
  3936. else:
  3937. return
  3938. else:
  3939. location = custom_location
  3940. self.jump_signal.emit(location)
  3941. if fit_center:
  3942. self.plotcanvas.fit_center(loc=location)
  3943. cursor = QtGui.QCursor()
  3944. if self.is_legacy is False:
  3945. # I don't know where those differences come from but they are constant for the current
  3946. # execution of the application and they are multiples of a value around 0.0263mm.
  3947. # In a random way sometimes they are more sometimes they are less
  3948. # if units == 'MM':
  3949. # cal_factor = 0.0263
  3950. # else:
  3951. # cal_factor = 0.0263 / 25.4
  3952. cal_location = (location[0], location[1])
  3953. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3954. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3955. j_pos = (
  3956. int(canvas_origin.x() + round(jump_loc[0])),
  3957. int(canvas_origin.y() + round(jump_loc[1]))
  3958. )
  3959. cursor.setPos(j_pos[0], j_pos[1])
  3960. else:
  3961. # find the canvas origin which is in the top left corner
  3962. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3963. # determine the coordinates for the lowest left point of the canvas
  3964. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3965. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3966. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3967. # canvas) and the point (width, height) is in the top-right location
  3968. loc = self.plotcanvas.axes.transData.transform_point(location)
  3969. j_pos = (
  3970. int(x0 + loc[0]),
  3971. int(y0 - loc[1])
  3972. )
  3973. cursor.setPos(j_pos[0], j_pos[1])
  3974. self.plotcanvas.mouse = [location[0], location[1]]
  3975. if self.defaults["global_cursor_color_enabled"] is True:
  3976. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3977. else:
  3978. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3979. if self.grid_status():
  3980. # Update cursor
  3981. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3982. symbol='++', edge_color=self.cursor_color_3D,
  3983. edge_width=self.defaults["global_cursor_width"],
  3984. size=self.defaults["global_cursor_size"])
  3985. # Set the relative position label
  3986. dx = location[0] - float(self.rel_point1[0])
  3987. dy = location[1] - float(self.rel_point1[1])
  3988. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3989. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3990. # Set the position label
  3991. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3992. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3993. units = self.defaults["units"].lower()
  3994. self.plotcanvas.text_hud.text = \
  3995. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3996. dx, units, dy, units, location[0], units, location[1], units)
  3997. self.inform.emit('[success] %s' % _("Done."))
  3998. return location
  3999. def on_locate(self, obj, fit_center=True):
  4000. """
  4001. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4002. :param obj: The object on which to locate certain points
  4003. :param fit_center: If to fit view. Boolean.
  4004. :return: A point location. (x, y) tuple.
  4005. """
  4006. self.defaults.report_usage("on_locate()")
  4007. if obj is None:
  4008. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4009. return 'fail'
  4010. class DialogBoxChoice(QtWidgets.QDialog):
  4011. def __init__(self, title=None, icon=None, choice='bl'):
  4012. """
  4013. :param title: string with the window title
  4014. """
  4015. super(DialogBoxChoice, self).__init__()
  4016. self.ok = False
  4017. self.setWindowIcon(icon)
  4018. self.setWindowTitle(str(title))
  4019. self.form = QtWidgets.QFormLayout(self)
  4020. self.ref_radio = RadioSet([
  4021. {"label": _("Bottom-Left"), "value": "bl"},
  4022. {"label": _("Top-Left"), "value": "tl"},
  4023. {"label": _("Bottom-Right"), "value": "br"},
  4024. {"label": _("Top-Right"), "value": "tr"},
  4025. {"label": _("Center"), "value": "c"}
  4026. ], orientation='vertical', stretch=False)
  4027. self.ref_radio.set_value(choice)
  4028. self.form.addRow(self.ref_radio)
  4029. self.button_box = QtWidgets.QDialogButtonBox(
  4030. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4031. Qt.Horizontal, parent=self)
  4032. self.form.addRow(self.button_box)
  4033. self.button_box.accepted.connect(self.accept)
  4034. self.button_box.rejected.connect(self.reject)
  4035. if self.exec_() == QtWidgets.QDialog.Accepted:
  4036. self.ok = True
  4037. self.location_point = self.ref_radio.get_value()
  4038. else:
  4039. self.ok = False
  4040. self.location_point = None
  4041. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4042. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4043. choice=self.defaults['global_locate_pt'])
  4044. if dia_box.ok is True:
  4045. try:
  4046. location_point = dia_box.location_point
  4047. self.defaults['global_locate_pt'] = dia_box.location_point
  4048. except Exception:
  4049. return
  4050. else:
  4051. return
  4052. loc_b = obj.bounds()
  4053. if location_point == 'bl':
  4054. location = (loc_b[0], loc_b[1])
  4055. elif location_point == 'tl':
  4056. location = (loc_b[0], loc_b[3])
  4057. elif location_point == 'br':
  4058. location = (loc_b[2], loc_b[1])
  4059. elif location_point == 'tr':
  4060. location = (loc_b[2], loc_b[3])
  4061. else:
  4062. # center
  4063. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4064. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4065. location = (cx, cy)
  4066. self.locate_signal.emit(location, location_point)
  4067. if fit_center:
  4068. self.plotcanvas.fit_center(loc=location)
  4069. cursor = QtGui.QCursor()
  4070. if self.is_legacy is False:
  4071. # I don't know where those differences come from but they are constant for the current
  4072. # execution of the application and they are multiples of a value around 0.0263mm.
  4073. # In a random way sometimes they are more sometimes they are less
  4074. # if units == 'MM':
  4075. # cal_factor = 0.0263
  4076. # else:
  4077. # cal_factor = 0.0263 / 25.4
  4078. cal_location = (location[0], location[1])
  4079. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4080. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4081. j_pos = (
  4082. int(canvas_origin.x() + round(jump_loc[0])),
  4083. int(canvas_origin.y() + round(jump_loc[1]))
  4084. )
  4085. cursor.setPos(j_pos[0], j_pos[1])
  4086. else:
  4087. # find the canvas origin which is in the top left corner
  4088. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4089. # determine the coordinates for the lowest left point of the canvas
  4090. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4091. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4092. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4093. # canvas) and the point (width, height) is in the top-right location
  4094. loc = self.plotcanvas.axes.transData.transform_point(location)
  4095. j_pos = (
  4096. int(x0 + loc[0]),
  4097. int(y0 - loc[1])
  4098. )
  4099. cursor.setPos(j_pos[0], j_pos[1])
  4100. self.plotcanvas.mouse = [location[0], location[1]]
  4101. if self.defaults["global_cursor_color_enabled"] is True:
  4102. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4103. else:
  4104. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4105. if self.grid_status():
  4106. # Update cursor
  4107. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4108. symbol='++', edge_color=self.cursor_color_3D,
  4109. edge_width=self.defaults["global_cursor_width"],
  4110. size=self.defaults["global_cursor_size"])
  4111. # Set the relative position label
  4112. self.dx = location[0] - float(self.rel_point1[0])
  4113. self.dy = location[1] - float(self.rel_point1[1])
  4114. # Set the position label
  4115. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4116. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4117. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4118. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4119. units = self.defaults["units"].lower()
  4120. self.plotcanvas.text_hud.text = \
  4121. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4122. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4123. self.inform.emit('[success] %s' % _("Done."))
  4124. return location
  4125. def on_copy_command(self):
  4126. """
  4127. Will copy a selection of objects, creating new objects.
  4128. :return:
  4129. """
  4130. self.defaults.report_usage("on_copy_command()")
  4131. def initialize(obj_init, app_obj):
  4132. """
  4133. :param obj_init: the new object
  4134. :type obj_init: class
  4135. :param app_obj: An instance of the App class
  4136. :type app_obj: App
  4137. :return: None
  4138. :rtype:
  4139. """
  4140. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4141. try:
  4142. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4143. except AttributeError:
  4144. pass
  4145. try:
  4146. obj_init.apertures = deepcopy(obj.apertures)
  4147. except AttributeError:
  4148. pass
  4149. try:
  4150. if obj.tools:
  4151. obj_init.tools = deepcopy(obj.tools)
  4152. except Exception as err:
  4153. app_obj.debug("App.on_copy_command() --> %s" % str(err))
  4154. try:
  4155. obj_init.source_file = deepcopy(obj.source_file)
  4156. except (AttributeError, TypeError):
  4157. pass
  4158. def initialize_excellon(obj_init, app_obj):
  4159. obj_init.source_file = deepcopy(obj.source_file)
  4160. obj_init.tools = deepcopy(obj.tools)
  4161. # drills are offset, so they need to be deep copied
  4162. obj_init.drills = deepcopy(obj.drills)
  4163. # slots are offset, so they need to be deep copied
  4164. obj_init.slots = deepcopy(obj.slots)
  4165. obj_init.create_geometry()
  4166. if not obj_init.tools:
  4167. app_obj.debug("on_copy_command() --> no excellon tools")
  4168. return 'fail'
  4169. def initialize_script(obj_init, app_obj):
  4170. obj_init.source_file = deepcopy(obj.source_file)
  4171. def initialize_document(obj_init, app_obj):
  4172. obj_init.source_file = deepcopy(obj.source_file)
  4173. for obj in self.collection.get_selected():
  4174. obj_name = obj.options["name"]
  4175. try:
  4176. if isinstance(obj, ExcellonObject):
  4177. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4178. elif isinstance(obj, GerberObject):
  4179. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4180. elif isinstance(obj, GeometryObject):
  4181. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4182. elif isinstance(obj, ScriptObject):
  4183. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4184. elif isinstance(obj, DocumentObject):
  4185. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4186. except Exception as e:
  4187. return "Operation failed: %s" % str(e)
  4188. def on_copy_object2(self, custom_name):
  4189. def initialize_geometry(obj_init, app_obj):
  4190. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4191. try:
  4192. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4193. except AttributeError:
  4194. pass
  4195. try:
  4196. obj_init.apertures = deepcopy(obj.apertures)
  4197. except AttributeError:
  4198. pass
  4199. try:
  4200. if obj.tools:
  4201. obj_init.tools = deepcopy(obj.tools)
  4202. except Exception as ee:
  4203. app_obj.debug("on_copy_object2() --> %s" % str(ee))
  4204. def initialize_gerber(obj_init, app_obj):
  4205. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4206. obj_init.apertures = deepcopy(obj.apertures)
  4207. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4208. if not obj_init.apertures:
  4209. app_obj.debug("on_copy_object2() --> no gerber apertures")
  4210. return 'fail'
  4211. def initialize_excellon(obj_init, app_obj):
  4212. obj_init.tools = deepcopy(obj.tools)
  4213. # drills are offset, so they need to be deep copied
  4214. obj_init.drills = deepcopy(obj.drills)
  4215. # slots are offset, so they need to be deep copied
  4216. obj_init.slots = deepcopy(obj.slots)
  4217. obj_init.create_geometry()
  4218. if not obj_init.tools:
  4219. app_obj.debug("on_copy_object2() --> no excellon tools")
  4220. return 'fail'
  4221. for obj in self.collection.get_selected():
  4222. obj_name = obj.options["name"]
  4223. try:
  4224. if isinstance(obj, ExcellonObject):
  4225. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4226. elif isinstance(obj, GerberObject):
  4227. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4228. elif isinstance(obj, GeometryObject):
  4229. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4230. except Exception as er:
  4231. return "Operation failed: %s" % str(er)
  4232. def on_rename_object(self, text):
  4233. """
  4234. Will rename an object.
  4235. :param text: New name for the object.
  4236. :return:
  4237. """
  4238. self.defaults.report_usage("on_rename_object()")
  4239. named_obj = self.collection.get_active()
  4240. for obj in named_obj:
  4241. if obj is list:
  4242. self.on_rename_object(text)
  4243. else:
  4244. try:
  4245. obj.options['name'] = text
  4246. except Exception as e:
  4247. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4248. def convert_any2geo(self):
  4249. """
  4250. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4251. :return:
  4252. """
  4253. self.defaults.report_usage("convert_any2geo()")
  4254. def initialize(obj_init, app):
  4255. obj_init.solid_geometry = obj.solid_geometry
  4256. try:
  4257. obj_init.follow_geometry = obj.follow_geometry
  4258. except AttributeError:
  4259. pass
  4260. try:
  4261. obj_init.apertures = obj.apertures
  4262. except AttributeError:
  4263. pass
  4264. try:
  4265. if obj.tools:
  4266. obj_init.tools = obj.tools
  4267. except AttributeError:
  4268. pass
  4269. def initialize_excellon(obj_init, app_obj):
  4270. # objs = self.collection.get_selected()
  4271. # GeometryObject.merge(objs, obj)
  4272. solid_geo = []
  4273. for tool in obj.tools:
  4274. for geo in obj.tools[tool]['solid_geometry']:
  4275. solid_geo.append(geo)
  4276. obj_init.solid_geometry = deepcopy(solid_geo)
  4277. if not obj_init.solid_geometry:
  4278. app_obj.log("convert_any2geo() failed")
  4279. return 'fail'
  4280. if not self.collection.get_selected():
  4281. log.warning("App.convert_any2geo --> No object selected")
  4282. self.inform.emit('[WARNING_NOTCL] %s' %
  4283. _("No object is selected. Select an object and try again."))
  4284. return
  4285. for obj in self.collection.get_selected():
  4286. obj_name = obj.options["name"]
  4287. try:
  4288. if obj.kind == 'excellon':
  4289. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4290. else:
  4291. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4292. except Exception as e:
  4293. return "Operation failed: %s" % str(e)
  4294. def convert_any2gerber(self):
  4295. """
  4296. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4297. :return:
  4298. """
  4299. def initialize_geometry(obj_init, app_obj):
  4300. apertures = {}
  4301. apid = 0
  4302. apertures[str(apid)] = {}
  4303. apertures[str(apid)]['geometry'] = []
  4304. for obj_orig in obj.solid_geometry:
  4305. new_elem = {}
  4306. new_elem['solid'] = obj_orig
  4307. try:
  4308. new_elem['follow'] = obj_orig.exterior
  4309. except AttributeError:
  4310. pass
  4311. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4312. apertures[str(apid)]['size'] = 0.0
  4313. apertures[str(apid)]['type'] = 'C'
  4314. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4315. obj_init.apertures = deepcopy(apertures)
  4316. if not obj_init.apertures:
  4317. app_obj.log("convert_any2gerber() failed")
  4318. return 'fail'
  4319. def initialize_excellon(obj_init, app_obj):
  4320. apertures = {}
  4321. apid = 10
  4322. for tool in obj.tools:
  4323. apertures[str(apid)] = {}
  4324. apertures[str(apid)]['geometry'] = []
  4325. for geo in obj.tools[tool]['solid_geometry']:
  4326. new_el = {}
  4327. new_el['solid'] = geo
  4328. new_el['follow'] = geo.exterior
  4329. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4330. apertures[str(apid)]['size'] = float(obj.tools[tool]['tooldia'])
  4331. apertures[str(apid)]['type'] = 'C'
  4332. apid += 1
  4333. # create solid_geometry
  4334. solid_geometry = []
  4335. for apid in apertures:
  4336. for geo_el in apertures[apid]['geometry']:
  4337. solid_geometry.append(geo_el['solid'])
  4338. solid_geometry = MultiPolygon(solid_geometry)
  4339. solid_geometry = solid_geometry.buffer(0.0000001)
  4340. obj_init.solid_geometry = deepcopy(solid_geometry)
  4341. obj_init.apertures = deepcopy(apertures)
  4342. if not obj_init.apertures:
  4343. app_obj.log("convert_any2gerber() failed")
  4344. return 'fail'
  4345. if not self.collection.get_selected():
  4346. log.warning("App.convert_any2gerber --> No object selected")
  4347. self.inform.emit('[WARNING_NOTCL] %s' %
  4348. _("No object is selected. Select an object and try again."))
  4349. return
  4350. for obj in self.collection.get_selected():
  4351. obj_name = obj.options["name"]
  4352. try:
  4353. if obj.kind == 'excellon':
  4354. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4355. elif obj.kind == 'geometry':
  4356. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4357. else:
  4358. log.warning("App.convert_any2gerber --> This is no valid object for conversion.")
  4359. except Exception as e:
  4360. return "Operation failed: %s" % str(e)
  4361. def convert_any2excellon(self):
  4362. """
  4363. Will convert any object out of Gerber, Excellon, Geometry to an Excellon object.
  4364. :return:
  4365. """
  4366. def initialize_geometry(obj_init, app_obj):
  4367. tools = {}
  4368. tooluid = 1
  4369. obj_init.solid_geometry = []
  4370. for geo in obj.solid_geometry:
  4371. if not isinstance(geo, (Polygon, MultiPolygon, LinearRing)):
  4372. continue
  4373. minx, miny, maxx, maxy = geo.bounds
  4374. new_dia = min([maxx-minx, maxy-miny])
  4375. new_drill = geo.centroid
  4376. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4377. current_tooldias = []
  4378. if tools:
  4379. for tool in tools:
  4380. if tools[tool] and 'tooldia' in tools[tool]:
  4381. current_tooldias.append(tools[tool]['tooldia'])
  4382. if new_dia in current_tooldias:
  4383. digits = app_obj.decimals
  4384. for tool in tools:
  4385. if app_obj.dec_format(tools[tool]["tooldia"], digits) == app_obj.dec_format(new_dia, digits):
  4386. tools[tool]['drills'].append(new_drill)
  4387. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4388. else:
  4389. tools[tooluid] = {}
  4390. tools[tooluid]['tooldia'] = new_dia
  4391. tools[tooluid]['drills'] = [new_drill]
  4392. tools[tooluid]['slots'] = []
  4393. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4394. tooluid += 1
  4395. try:
  4396. obj_init.solid_geometry.append(new_drill_geo)
  4397. except (TypeError, AttributeError):
  4398. obj_init.solid_geometry = [new_drill_geo]
  4399. obj_init.tools = deepcopy(tools)
  4400. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4401. if not obj_init.solid_geometry:
  4402. return 'fail'
  4403. def initialize_gerber(obj_init, app_obj):
  4404. tools = {}
  4405. tooluid = 1
  4406. digits = app_obj.decimals
  4407. obj_init.solid_geometry = []
  4408. for apid in obj.apertures:
  4409. if 'geometry' in obj.apertures[apid]:
  4410. for geo_dict in obj.apertures[apid]['geometry']:
  4411. if 'follow' in geo_dict:
  4412. if isinstance(geo_dict['follow'], Point):
  4413. geo = geo_dict['solid']
  4414. minx, miny, maxx, maxy = geo.bounds
  4415. new_dia = min([maxx - minx, maxy - miny])
  4416. new_drill = geo.centroid
  4417. new_drill_geo = new_drill.buffer(new_dia / 2.0)
  4418. current_tooldias = []
  4419. if tools:
  4420. for tool in tools:
  4421. if tools[tool] and 'tooldia' in tools[tool]:
  4422. current_tooldias.append(
  4423. app_obj.dec_format(tools[tool]['tooldia'], digits)
  4424. )
  4425. formatted_new_dia = app_obj.dec_format(new_dia, digits)
  4426. if formatted_new_dia in current_tooldias:
  4427. for tool in tools:
  4428. if app_obj.dec_format(tools[tool]["tooldia"], digits) == formatted_new_dia:
  4429. if new_drill not in tools[tool]['drills']:
  4430. tools[tool]['drills'].append(new_drill)
  4431. tools[tool]['solid_geometry'].append(deepcopy(new_drill_geo))
  4432. else:
  4433. tools[tooluid] = {}
  4434. tools[tooluid]['tooldia'] = new_dia
  4435. tools[tooluid]['drills'] = [new_drill]
  4436. tools[tooluid]['slots'] = []
  4437. tools[tooluid]['solid_geometry'] = [new_drill_geo]
  4438. tooluid += 1
  4439. try:
  4440. obj_init.solid_geometry.append(new_drill_geo)
  4441. except (TypeError, AttributeError):
  4442. obj_init.solid_geometry = [new_drill_geo]
  4443. elif isinstance(geo_dict['follow'], LineString):
  4444. geo_coords = list(geo_dict['follow'].coords)
  4445. # slots can have only a start and stop point and no intermediate points
  4446. if len(geo_coords) != 2:
  4447. continue
  4448. geo = geo_dict['solid']
  4449. try:
  4450. new_dia = obj.apertures[apid]['size']
  4451. except Exception:
  4452. continue
  4453. new_slot = (Point(geo_coords[0]), Point(geo_coords[1]))
  4454. new_slot_geo = geo
  4455. current_tooldias = []
  4456. if tools:
  4457. for tool in tools:
  4458. if tools[tool] and 'tooldia' in tools[tool]:
  4459. current_tooldias.append(
  4460. float('%.*f' % (self.decimals, tools[tool]['tooldia']))
  4461. )
  4462. if float('%.*f' % (self.decimals, new_dia)) in current_tooldias:
  4463. for tool in tools:
  4464. if float('%.*f' % (self.decimals, tools[tool]["tooldia"])) == float(
  4465. '%.*f' % (self.decimals, new_dia)):
  4466. if new_slot not in tools[tool]['slots']:
  4467. tools[tool]['slots'].append(new_slot)
  4468. tools[tool]['solid_geometry'].append(deepcopy(new_slot_geo))
  4469. else:
  4470. tools[tooluid] = {}
  4471. tools[tooluid]['tooldia'] = new_dia
  4472. tools[tooluid]['drills'] = []
  4473. tools[tooluid]['slots'] = [new_slot]
  4474. tools[tooluid]['solid_geometry'] = [new_slot_geo]
  4475. tooluid += 1
  4476. try:
  4477. obj_init.solid_geometry.append(new_slot_geo)
  4478. except (TypeError, AttributeError):
  4479. obj_init.solid_geometry = [new_slot_geo]
  4480. obj_init.tools = deepcopy(tools)
  4481. obj_init.solid_geometry = unary_union(obj_init.solid_geometry)
  4482. if not obj_init.solid_geometry:
  4483. return 'fail'
  4484. if not self.collection.get_selected():
  4485. log.warning("App.convert_any2excellon--> No object selected")
  4486. self.inform.emit('[WARNING_NOTCL] %s' % _("No object is selected. Select an object and try again."))
  4487. return
  4488. for obj in self.collection.get_selected():
  4489. obj_name = obj.options["name"]
  4490. try:
  4491. if obj.kind == 'gerber':
  4492. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_gerber)
  4493. elif obj.kind == 'geometry':
  4494. self.app_obj.new_object("excellon", str(obj_name) + "_conv", initialize_geometry)
  4495. else:
  4496. log.warning("App.convert_any2excellon --> This is no valid object for conversion.")
  4497. except Exception as e:
  4498. return "Operation failed: %s" % str(e)
  4499. def abort_all_tasks(self):
  4500. """
  4501. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4502. on the first possible occasion.
  4503. :return:
  4504. """
  4505. if self.abort_flag is False:
  4506. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4507. self.abort_flag = True
  4508. self.cleanup.emit()
  4509. def app_is_idle(self):
  4510. if self.abort_flag:
  4511. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4512. self.abort_flag = False
  4513. def on_selectall(self):
  4514. """
  4515. Will draw a selection box shape around the selected objects.
  4516. :return:
  4517. """
  4518. self.defaults.report_usage("on_selectall()")
  4519. # delete the possible selection box around a possible selected object
  4520. self.delete_selection_shape()
  4521. for name in self.collection.get_names():
  4522. self.collection.set_active(name)
  4523. curr_sel_obj = self.collection.get_by_name(name)
  4524. # create the selection box around the selected object
  4525. if self.defaults['global_selection_shape'] is True:
  4526. self.draw_selection_shape(curr_sel_obj)
  4527. def on_toggle_preferences(self):
  4528. pref_open = False
  4529. for idx in range(self.ui.plot_tab_area.count()):
  4530. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4531. pref_open = True
  4532. if pref_open:
  4533. for idx in range(self.ui.plot_tab_area.count()):
  4534. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4535. self.ui.plot_tab_area.removeTab(idx)
  4536. break
  4537. self.ui.pref_status_label.setStyleSheet("")
  4538. else:
  4539. self.on_preferences()
  4540. def on_preferences(self):
  4541. """
  4542. Adds the Preferences in a Tab in Plot Area
  4543. :return:
  4544. """
  4545. # add the tab if it was closed
  4546. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4547. # delete the absolute and relative position and messages in the infobar
  4548. # self.ui.position_label.setText("")
  4549. # self.ui.rel_position_label.setText("")
  4550. # hide coordinates toolbars in the infobar while in DB
  4551. self.ui.coords_toolbar.hide()
  4552. self.ui.delta_coords_toolbar.hide()
  4553. # Switch plot_area to preferences page
  4554. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4555. # self.ui.show()
  4556. self.ui.pref_status_label.setStyleSheet("""
  4557. QLabel
  4558. {
  4559. color: black;
  4560. background-color: lightseagreen;
  4561. }
  4562. """
  4563. )
  4564. # detect changes in the preferences
  4565. for idx in range(self.ui.pref_tab_area.count()):
  4566. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4567. try:
  4568. try:
  4569. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4570. except (TypeError, AttributeError):
  4571. pass
  4572. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4573. except AttributeError:
  4574. pass
  4575. try:
  4576. try:
  4577. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4578. except (TypeError, AttributeError):
  4579. pass
  4580. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4581. except AttributeError:
  4582. pass
  4583. try:
  4584. try:
  4585. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4586. except (TypeError, AttributeError):
  4587. pass
  4588. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4589. except AttributeError:
  4590. pass
  4591. try:
  4592. try:
  4593. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4594. except (TypeError, AttributeError):
  4595. pass
  4596. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4597. except AttributeError:
  4598. pass
  4599. try:
  4600. try:
  4601. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4602. except (TypeError, AttributeError):
  4603. pass
  4604. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4605. except AttributeError:
  4606. pass
  4607. def on_tools_database(self, source='app'):
  4608. """
  4609. Adds the Tools Database in a Tab in Plot Area.
  4610. :return:
  4611. """
  4612. filename = self.tools_database_path()
  4613. # load the database tools from the file
  4614. try:
  4615. with open(filename) as f:
  4616. __ = f.read()
  4617. except Exception as eros:
  4618. self.log.debug("The tools DB file is not loaded: %s" % str(eros))
  4619. log.error("Could not access tools DB file. The file may be locked,\n"
  4620. "not existing or doesn't have the read permissions.\n"
  4621. "Check to see if exists, it should be here: %s\n"
  4622. "It may help to reboot the app, it will try to recreate it if it's missing." % self.data_path)
  4623. self.inform.emit('[ERROR] %s' % _("Could not load Tools DB file."))
  4624. return 'fail'
  4625. for idx in range(self.ui.plot_tab_area.count()):
  4626. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4627. # there can be only one instance of Tools Database at one time
  4628. return
  4629. if source == 'app':
  4630. self.tools_db_tab = ToolsDB2(
  4631. app=self,
  4632. parent=self.ui,
  4633. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4634. )
  4635. elif source == 'ncc':
  4636. self.tools_db_tab = ToolsDB2(
  4637. app=self,
  4638. parent=self.ui,
  4639. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4640. )
  4641. elif source == 'paint':
  4642. self.tools_db_tab = ToolsDB2(
  4643. app=self,
  4644. parent=self.ui,
  4645. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4646. )
  4647. elif source == 'iso':
  4648. self.tools_db_tab = ToolsDB2(
  4649. app=self,
  4650. parent=self.ui,
  4651. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4652. )
  4653. elif source == 'cutout':
  4654. self.tools_db_tab = ToolsDB2(
  4655. app=self,
  4656. parent=self.ui,
  4657. callback_on_tool_request=self.cutout_tool.on_cutout_tool_add_from_db_executed
  4658. )
  4659. # add the tab if it was closed
  4660. try:
  4661. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4662. self.tools_db_tab.setObjectName("database_tab")
  4663. except Exception as e:
  4664. self.log.debug("App.on_tools_database() --> %s" % str(e))
  4665. return
  4666. # delete the absolute and relative position and messages in the infobar
  4667. # self.ui.position_label.setText("")
  4668. # self.ui.rel_position_label.setText("")
  4669. # hide coordinates toolbars in the infobar while in DB
  4670. self.ui.coords_toolbar.hide()
  4671. self.ui.delta_coords_toolbar.hide()
  4672. # Switch plot_area to preferences page
  4673. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4674. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4675. self.tools_db_tab.ui_connect()
  4676. def on_geometry_tool_add_from_db_executed(self, tool):
  4677. """
  4678. Here add the tool from DB in the selected geometry object.
  4679. :return:
  4680. """
  4681. tool_from_db = deepcopy(tool)
  4682. obj = self.collection.get_active()
  4683. if obj.kind == 'geometry':
  4684. if tool['data']['tool_target'] not in [0, 1]: # General, Milling Type
  4685. # close the tab and delete it
  4686. for idx in range(self.ui.plot_tab_area.count()):
  4687. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4688. wdg = self.ui.plot_tab_area.widget(idx)
  4689. wdg.deleteLater()
  4690. self.ui.plot_tab_area.removeTab(idx)
  4691. self.inform.emit('[ERROR_NOTCL] %s' % _("Selected tool can't be used here. Pick another."))
  4692. return
  4693. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4694. # close the tab and delete it
  4695. for idx in range(self.ui.plot_tab_area.count()):
  4696. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4697. wdg = self.ui.plot_tab_area.widget(idx)
  4698. wdg.deleteLater()
  4699. self.ui.plot_tab_area.removeTab(idx)
  4700. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4701. elif obj.kind == 'gerber':
  4702. if tool['data']['tool_target'] not in [0, 3]: # General, Isolation Type
  4703. # close the tab and delete it
  4704. for idx in range(self.ui.plot_tab_area.count()):
  4705. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4706. wdg = self.ui.plot_tab_area.widget(idx)
  4707. wdg.deleteLater()
  4708. self.ui.plot_tab_area.removeTab(idx)
  4709. self.inform.emit('[ERROR_NOTCL] %s' % _("Selected tool can't be used here. Pick another."))
  4710. return
  4711. self.isolation_tool.on_tool_from_db_inserted(tool=tool_from_db)
  4712. # close the tab and delete it
  4713. for idx in range(self.ui.plot_tab_area.count()):
  4714. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4715. wdg = self.ui.plot_tab_area.widget(idx)
  4716. wdg.deleteLater()
  4717. self.ui.plot_tab_area.removeTab(idx)
  4718. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4719. else:
  4720. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4721. def on_plot_area_tab_closed(self, tab_obj_name):
  4722. """
  4723. Executed whenever a QTab is closed in the Plot Area.
  4724. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4725. :return:
  4726. """
  4727. if tab_obj_name == "preferences_tab":
  4728. self.preferencesUiManager.on_close_preferences_tab()
  4729. elif tab_obj_name == "database_tab":
  4730. # disconnect the signals from the table widget in tab
  4731. self.tools_db_tab.ui_disconnect()
  4732. if self.tools_db_changed_flag is True:
  4733. msgbox = QtWidgets.QMessageBox()
  4734. msgbox.setText(_("One or more Tools are edited.\n"
  4735. "Do you want to update the Tools Database?"))
  4736. msgbox.setWindowTitle(_("Save Tools Database"))
  4737. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4738. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4739. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4740. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4741. msgbox.setDefaultButton(bt_yes)
  4742. msgbox.exec_()
  4743. response = msgbox.clickedButton()
  4744. if response == bt_yes:
  4745. self.tools_db_tab.on_save_tools_db()
  4746. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4747. else:
  4748. self.tools_db_changed_flag = False
  4749. self.inform.emit('')
  4750. return
  4751. self.tools_db_tab.deleteLater()
  4752. elif tab_obj_name == "text_editor_tab":
  4753. self.toggle_codeeditor = False
  4754. elif tab_obj_name == "bookmarks_tab":
  4755. self.book_dialog_tab.rebuild_actions()
  4756. self.book_dialog_tab.deleteLater()
  4757. else:
  4758. pass
  4759. # restore the coords toolbars
  4760. self.ui.toggle_coords(checked=self.defaults["global_coordsbar_show"])
  4761. self.ui.toggle_delta_coords(checked=self.defaults["global_delta_coordsbar_show"])
  4762. def on_flipy(self):
  4763. """
  4764. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4765. :return:
  4766. """
  4767. self.defaults.report_usage("on_flipy()")
  4768. obj_list = self.collection.get_selected()
  4769. xminlist = []
  4770. yminlist = []
  4771. xmaxlist = []
  4772. ymaxlist = []
  4773. if not obj_list:
  4774. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4775. else:
  4776. try:
  4777. # first get a bounding box to fit all
  4778. for obj in obj_list:
  4779. xmin, ymin, xmax, ymax = obj.bounds()
  4780. xminlist.append(xmin)
  4781. yminlist.append(ymin)
  4782. xmaxlist.append(xmax)
  4783. ymaxlist.append(ymax)
  4784. # get the minimum x,y and maximum x,y for all objects selected
  4785. xminimal = min(xminlist)
  4786. yminimal = min(yminlist)
  4787. xmaximal = max(xmaxlist)
  4788. ymaximal = max(ymaxlist)
  4789. px = 0.5 * (xminimal + xmaximal)
  4790. py = 0.5 * (yminimal + ymaximal)
  4791. # execute mirroring
  4792. for obj in obj_list:
  4793. obj.mirror('X', [px, py])
  4794. obj.plot()
  4795. self.app_obj.object_changed.emit(obj)
  4796. self.inform.emit('[success] %s' %
  4797. _("Flip on Y axis done."))
  4798. except Exception as e:
  4799. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4800. return
  4801. def on_flipx(self):
  4802. """
  4803. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4804. :return:
  4805. """
  4806. self.defaults.report_usage("on_flipx()")
  4807. obj_list = self.collection.get_selected()
  4808. xminlist = []
  4809. yminlist = []
  4810. xmaxlist = []
  4811. ymaxlist = []
  4812. if not obj_list:
  4813. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on X axis."))
  4814. else:
  4815. try:
  4816. # first get a bounding box to fit all
  4817. for obj in obj_list:
  4818. xmin, ymin, xmax, ymax = obj.bounds()
  4819. xminlist.append(xmin)
  4820. yminlist.append(ymin)
  4821. xmaxlist.append(xmax)
  4822. ymaxlist.append(ymax)
  4823. # get the minimum x,y and maximum x,y for all objects selected
  4824. xminimal = min(xminlist)
  4825. yminimal = min(yminlist)
  4826. xmaximal = max(xmaxlist)
  4827. ymaximal = max(ymaxlist)
  4828. px = 0.5 * (xminimal + xmaximal)
  4829. py = 0.5 * (yminimal + ymaximal)
  4830. # execute mirroring
  4831. for obj in obj_list:
  4832. obj.mirror('Y', [px, py])
  4833. obj.plot()
  4834. self.app_obj.object_changed.emit(obj)
  4835. self.inform.emit('[success] %s' %
  4836. _("Flip on X axis done."))
  4837. except Exception as e:
  4838. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4839. return
  4840. def on_rotate(self, silent=False, preset=None):
  4841. """
  4842. Executed when Options -> Rotate Selection menu entry is clicked.
  4843. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4844. :param preset: A value to be used as predefined angle for rotation.
  4845. :return:
  4846. """
  4847. self.defaults.report_usage("on_rotate()")
  4848. obj_list = self.collection.get_selected()
  4849. xminlist = []
  4850. yminlist = []
  4851. xmaxlist = []
  4852. ymaxlist = []
  4853. if not obj_list:
  4854. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4855. else:
  4856. if silent is False:
  4857. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4858. min=-360, max=360, decimals=4,
  4859. init_val=float(self.defaults['tools_transform_rotate']))
  4860. num, ok = rotatebox.get_value()
  4861. else:
  4862. num = preset
  4863. ok = True
  4864. if ok:
  4865. try:
  4866. # first get a bounding box to fit all
  4867. for obj in obj_list:
  4868. xmin, ymin, xmax, ymax = obj.bounds()
  4869. xminlist.append(xmin)
  4870. yminlist.append(ymin)
  4871. xmaxlist.append(xmax)
  4872. ymaxlist.append(ymax)
  4873. # get the minimum x,y and maximum x,y for all objects selected
  4874. xminimal = min(xminlist)
  4875. yminimal = min(yminlist)
  4876. xmaximal = max(xmaxlist)
  4877. ymaximal = max(ymaxlist)
  4878. px = 0.5 * (xminimal + xmaximal)
  4879. py = 0.5 * (yminimal + ymaximal)
  4880. for sel_obj in obj_list:
  4881. sel_obj.rotate(-float(num), point=(px, py))
  4882. sel_obj.plot()
  4883. self.app_obj.object_changed.emit(sel_obj)
  4884. self.inform.emit('[success] %s' % _("Rotation done."))
  4885. except Exception as e:
  4886. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4887. return
  4888. def on_skewx(self):
  4889. """
  4890. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4891. :return:
  4892. """
  4893. self.defaults.report_usage("on_skewx()")
  4894. obj_list = self.collection.get_selected()
  4895. xminlist = []
  4896. yminlist = []
  4897. if not obj_list:
  4898. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4899. else:
  4900. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4901. min=-360, max=360, decimals=4,
  4902. init_val=float(self.defaults['tools_transform_skew_x']))
  4903. num, ok = skewxbox.get_value()
  4904. if ok:
  4905. # first get a bounding box to fit all
  4906. for obj in obj_list:
  4907. xmin, ymin, xmax, ymax = obj.bounds()
  4908. xminlist.append(xmin)
  4909. yminlist.append(ymin)
  4910. # get the minimum x,y and maximum x,y for all objects selected
  4911. xminimal = min(xminlist)
  4912. yminimal = min(yminlist)
  4913. for obj in obj_list:
  4914. obj.skew(num, 0, point=(xminimal, yminimal))
  4915. obj.plot()
  4916. self.app_obj.object_changed.emit(obj)
  4917. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4918. def on_skewy(self):
  4919. """
  4920. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4921. :return:
  4922. """
  4923. self.defaults.report_usage("on_skewy()")
  4924. obj_list = self.collection.get_selected()
  4925. xminlist = []
  4926. yminlist = []
  4927. if not obj_list:
  4928. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4929. else:
  4930. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4931. min=-360, max=360, decimals=4,
  4932. init_val=float(self.defaults['tools_transform_skew_y']))
  4933. num, ok = skewybox.get_value()
  4934. if ok:
  4935. # first get a bounding box to fit all
  4936. for obj in obj_list:
  4937. xmin, ymin, xmax, ymax = obj.bounds()
  4938. xminlist.append(xmin)
  4939. yminlist.append(ymin)
  4940. # get the minimum x,y and maximum x,y for all objects selected
  4941. xminimal = min(xminlist)
  4942. yminimal = min(yminlist)
  4943. for obj in obj_list:
  4944. obj.skew(0, num, point=(xminimal, yminimal))
  4945. obj.plot()
  4946. self.app_obj.object_changed.emit(obj)
  4947. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4948. def on_plots_updated(self):
  4949. """
  4950. Callback used to report when the plots have changed.
  4951. Adjust axes and zooms to fit.
  4952. :return: None
  4953. """
  4954. if self.is_legacy is False:
  4955. self.plotcanvas.update()
  4956. else:
  4957. self.plotcanvas.auto_adjust_axes()
  4958. self.on_zoom_fit()
  4959. self.collection.update_view()
  4960. # self.inform.emit(_("Plots updated ..."))
  4961. def on_toolbar_replot(self):
  4962. """
  4963. Callback for toolbar button. Re-plots all objects.
  4964. :return: None
  4965. """
  4966. self.log.debug("on_toolbar_replot()")
  4967. try:
  4968. obj = self.collection.get_active()
  4969. if obj:
  4970. obj.read_form()
  4971. else:
  4972. self.on_zoom_fit()
  4973. except AttributeError as e:
  4974. self.log.debug("on_toolbar_replot() -> %s" % str(e))
  4975. pass
  4976. self.plot_all()
  4977. def grid_status(self):
  4978. return True if self.ui.grid_snap_btn.isChecked() else False
  4979. def populate_cmenu_grids(self):
  4980. units = self.defaults['units'].lower()
  4981. # for act in self.ui.cmenu_gridmenu.actions():
  4982. # act.triggered.disconnect()
  4983. self.ui.cmenu_gridmenu.clear()
  4984. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4985. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4986. _("Grid On/Off"))
  4987. grid_toggle.setCheckable(True)
  4988. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4989. self.ui.cmenu_gridmenu.addSeparator()
  4990. for grid in sorted_list:
  4991. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4992. "%s" % str(grid))
  4993. action.triggered.connect(self.set_grid)
  4994. self.ui.cmenu_gridmenu.addSeparator()
  4995. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4996. _("Add"))
  4997. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4998. _("Delete"))
  4999. grid_add.triggered.connect(self.on_grid_add)
  5000. grid_delete.triggered.connect(self.on_grid_delete)
  5001. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5002. def set_grid(self):
  5003. menu_action = self.sender()
  5004. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5005. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5006. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5007. def on_grid_add(self):
  5008. # ## Current application units in lower Case
  5009. units = self.defaults['units'].lower()
  5010. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5011. text=_('Enter a Grid Value:'),
  5012. min=0.0000, max=99.9999, decimals=4)
  5013. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5014. val, ok = grid_add_popup.get_value()
  5015. if ok:
  5016. if float(val) == 0:
  5017. self.inform.emit('[WARNING_NOTCL] %s' %
  5018. _("Please enter a grid value with non-zero value, in Float format."))
  5019. return
  5020. else:
  5021. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5022. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5023. self.inform.emit('[success] %s...' % _("New Grid added"))
  5024. else:
  5025. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  5026. else:
  5027. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  5028. def on_grid_delete(self):
  5029. # ## Current application units in lower Case
  5030. units = self.defaults['units'].lower()
  5031. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5032. text='Enter a Grid Value:',
  5033. min=0.0000, max=99.9999, decimals=4)
  5034. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5035. val, ok = grid_del_popup.get_value()
  5036. if ok:
  5037. if float(val) == 0:
  5038. self.inform.emit('[WARNING_NOTCL] %s' %
  5039. _("Please enter a grid value with non-zero value, in Float format."))
  5040. return
  5041. else:
  5042. try:
  5043. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5044. except ValueError:
  5045. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  5046. return
  5047. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  5048. else:
  5049. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  5050. def on_shortcut_list(self):
  5051. self.defaults.report_usage("on_shortcut_list()")
  5052. # add the tab if it was closed
  5053. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5054. # delete the absolute and relative position and messages in the infobar
  5055. # self.ui.position_label.setText("")
  5056. # self.ui.rel_position_label.setText("")
  5057. # hide coordinates toolbars in the infobar while in DB
  5058. self.ui.coords_toolbar.hide()
  5059. self.ui.delta_coords_toolbar.hide()
  5060. # Switch plot_area to preferences page
  5061. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5062. # self.ui.show()
  5063. def on_select_tab(self, name):
  5064. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5065. if self.ui.splitter.sizes()[0] == 0:
  5066. self.ui.splitter.setSizes([1, 1])
  5067. else:
  5068. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5069. self.ui.splitter.setSizes([0, 1])
  5070. if name == 'project':
  5071. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5072. elif name == 'properties':
  5073. self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  5074. elif name == 'tool':
  5075. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5076. def on_copy_name(self):
  5077. self.defaults.report_usage("on_copy_name()")
  5078. obj = self.collection.get_active()
  5079. try:
  5080. name = obj.options["name"]
  5081. except AttributeError:
  5082. self.log.debug("on_copy_name() --> No object selected to copy it's name")
  5083. self.inform.emit('[WARNING_NOTCL] %s' %
  5084. _(" No object selected to copy it's name"))
  5085. return
  5086. self.clipboard.setText(name)
  5087. self.inform.emit(_("Name copied on clipboard ..."))
  5088. def on_mouse_click_over_plot(self, event):
  5089. """
  5090. Default actions are:
  5091. :param event: Contains information about the event, like which button
  5092. was clicked, the pixel coordinates and the axes coordinates.
  5093. :return: None
  5094. """
  5095. self.pos = []
  5096. if self.is_legacy is False:
  5097. event_pos = event.pos
  5098. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5099. # # Set the mouse button for panning
  5100. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5101. else:
  5102. event_pos = (event.xdata, event.ydata)
  5103. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5104. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5105. # So it can receive key presses
  5106. self.plotcanvas.native.setFocus()
  5107. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5108. if self.grid_status():
  5109. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5110. else:
  5111. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5112. try:
  5113. if event.button == 1:
  5114. # Reset here the relative coordinates so there is a new reference on the click position
  5115. if self.rel_point1 is None:
  5116. self.rel_point1 = self.pos
  5117. else:
  5118. self.rel_point2 = copy(self.rel_point1)
  5119. self.rel_point1 = self.pos
  5120. self.on_mouse_move_over_plot(event, origin_click=True)
  5121. except Exception as e:
  5122. self.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5123. def on_mouse_double_click_over_plot(self, event):
  5124. if event.button == 1:
  5125. self.doubleclick = True
  5126. def on_mouse_move_over_plot(self, event, origin_click=None):
  5127. """
  5128. Callback for the mouse motion event over the plot.
  5129. :param event: Contains information about the event.
  5130. :param origin_click
  5131. :return: None
  5132. """
  5133. if self.is_legacy is False:
  5134. event_pos = event.pos
  5135. if self.defaults["global_pan_button"] == '2':
  5136. pan_button = 2
  5137. else:
  5138. pan_button = 3
  5139. self.event_is_dragging = event.is_dragging
  5140. else:
  5141. event_pos = (event.xdata, event.ydata)
  5142. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5143. if self.defaults["global_pan_button"] == '2':
  5144. pan_button = 3
  5145. else:
  5146. pan_button = 2
  5147. self.event_is_dragging = self.plotcanvas.is_dragging
  5148. # So it can receive key presses but not when the Tcl Shell is active
  5149. if not self.ui.shell_dock.isVisible():
  5150. if not self.plotcanvas.native.hasFocus():
  5151. self.plotcanvas.native.setFocus()
  5152. self.pos_jump = event_pos
  5153. self.ui.popMenu.mouse_is_panning = False
  5154. if origin_click is None:
  5155. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5156. if event.button == pan_button and self.event_is_dragging == 1:
  5157. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5158. if self.ui.popMenu.popup_active:
  5159. self.ui.popMenu.popup_active = False
  5160. return
  5161. self.ui.popMenu.mouse_is_panning = True
  5162. return
  5163. if self.rel_point1 is not None:
  5164. try: # May fail in case mouse not within axes
  5165. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5166. if pos_canvas[0] is None or pos_canvas[1] is None:
  5167. return
  5168. if self.grid_status():
  5169. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5170. # Update cursor
  5171. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5172. symbol='++', edge_color=self.cursor_color_3D,
  5173. edge_width=self.defaults["global_cursor_width"],
  5174. size=self.defaults["global_cursor_size"])
  5175. else:
  5176. pos = (pos_canvas[0], pos_canvas[1])
  5177. self.dx = pos[0] - float(self.rel_point1[0])
  5178. self.dy = pos[1] - float(self.rel_point1[1])
  5179. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5180. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  5181. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5182. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5183. units = self.defaults["units"].lower()
  5184. self.plotcanvas.text_hud.text = \
  5185. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5186. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5187. self.mouse = [pos[0], pos[1]]
  5188. if self.defaults['global_selection_shape'] is False:
  5189. self.selection_type = None
  5190. return
  5191. # if the mouse is moved and the LMB is clicked then the action is a selection
  5192. if self.event_is_dragging == 1 and event.button == 1:
  5193. self.delete_selection_shape()
  5194. if self.dx < 0:
  5195. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5196. face_color=self.defaults['global_alt_sel_fill'])
  5197. self.selection_type = False
  5198. elif self.dx >= 0:
  5199. self.draw_moving_selection_shape(self.pos, pos)
  5200. self.selection_type = True
  5201. else:
  5202. self.selection_type = None
  5203. else:
  5204. self.selection_type = None
  5205. # hover effect - enabled in Preferences -> General -> appGUI Settings
  5206. if self.defaults['global_hover']:
  5207. for obj in self.collection.get_list():
  5208. try:
  5209. # select the object(s) only if it is enabled (plotted)
  5210. if obj.options['plot']:
  5211. if obj not in self.collection.get_selected():
  5212. poly_obj = Polygon(
  5213. [(obj.options['xmin'], obj.options['ymin']),
  5214. (obj.options['xmax'], obj.options['ymin']),
  5215. (obj.options['xmax'], obj.options['ymax']),
  5216. (obj.options['xmin'], obj.options['ymax'])]
  5217. )
  5218. if Point(pos).within(poly_obj):
  5219. if obj.isHovering is False:
  5220. obj.isHovering = True
  5221. obj.notHovering = True
  5222. # create the selection box around the selected object
  5223. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5224. else:
  5225. if obj.notHovering is True:
  5226. obj.notHovering = False
  5227. obj.isHovering = False
  5228. self.delete_hover_shape()
  5229. except Exception:
  5230. # the Exception here will happen if we try to select on screen and we have an
  5231. # newly (and empty) just created Geometry or Excellon object that do not have the
  5232. # xmin, xmax, ymin, ymax options.
  5233. # In this case poly_obj creation (see above) will fail
  5234. pass
  5235. except Exception as e:
  5236. self.log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5237. self.ui.position_label.setText("")
  5238. self.ui.rel_position_label.setText("")
  5239. self.mouse = None
  5240. def on_mouse_click_release_over_plot(self, event):
  5241. """
  5242. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5243. and has been registered in ''self.__init__()''.
  5244. :param event: contains information about the event.
  5245. :return:
  5246. """
  5247. if self.is_legacy is False:
  5248. event_pos = event.pos
  5249. right_button = 2
  5250. else:
  5251. event_pos = (event.xdata, event.ydata)
  5252. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5253. right_button = 3
  5254. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5255. if self.grid_status():
  5256. try:
  5257. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5258. except TypeError:
  5259. return
  5260. else:
  5261. pos = (pos_canvas[0], pos_canvas[1])
  5262. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5263. # canvas menu
  5264. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5265. self.ui.popMenu.mouse_is_panning = False
  5266. self.cursor = QtGui.QCursor()
  5267. self.populate_cmenu_grids()
  5268. self.ui.popMenu.popup(self.cursor.pos())
  5269. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5270. # selection and then select a type of selection ("enclosing" or "touching")
  5271. if event.button == 1: # left click
  5272. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5273. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5274. if modifiers == QtCore.Qt.ShiftModifier:
  5275. # do not auto open the Project Tab
  5276. self.click_noproject = True
  5277. self.clipboard.setText(
  5278. self.defaults["global_point_clipboard_format"] %
  5279. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5280. )
  5281. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5282. return
  5283. if self.doubleclick is True:
  5284. self.doubleclick = False
  5285. if self.collection.get_selected():
  5286. self.ui.notebook.setCurrentWidget(self.ui.properties_tab)
  5287. if self.ui.splitter.sizes()[0] == 0:
  5288. self.ui.splitter.setSizes([1, 1])
  5289. try:
  5290. # delete the selection shape(S) as it may be in the way
  5291. self.delete_selection_shape()
  5292. self.delete_hover_shape()
  5293. except Exception as e:
  5294. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5295. return
  5296. else:
  5297. # WORKAROUND for LEGACY MODE
  5298. if self.is_legacy is True:
  5299. # if there is no move on canvas then we have no dragging selection
  5300. if self.dx == 0 or self.dy == 0:
  5301. self.selection_type = None
  5302. if self.selection_type is not None:
  5303. try:
  5304. self.selection_area_handler(self.pos, pos, self.selection_type)
  5305. self.selection_type = None
  5306. except Exception as e:
  5307. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5308. return
  5309. else:
  5310. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5311. if key_modifier == QtCore.Qt.ShiftModifier:
  5312. mod_key = 'Shift'
  5313. elif key_modifier == QtCore.Qt.ControlModifier:
  5314. mod_key = 'Control'
  5315. else:
  5316. mod_key = None
  5317. try:
  5318. if self.command_active is None:
  5319. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5320. # deselect, and if it's not selected then it will be selected
  5321. # If there is no active command (self.command_active is None) then we check if we clicked
  5322. # on a object by checking the bounding limits against mouse click position
  5323. if mod_key == self.defaults["global_mselect_key"]:
  5324. self.select_objects(key='multisel')
  5325. else:
  5326. # If there is no active command (self.command_active is None) then we check if
  5327. # we clicked on a object by checking the bounding limits against mouse click position
  5328. self.select_objects()
  5329. self.delete_hover_shape()
  5330. except Exception as e:
  5331. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5332. return
  5333. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5334. """
  5335. :param start_pos: mouse position when the selection LMB click was done
  5336. :param end_pos: mouse position when the left mouse button is released
  5337. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5338. :return:
  5339. """
  5340. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5341. # delete previous selection shape
  5342. self.delete_selection_shape()
  5343. # make all objects inactive
  5344. self.collection.set_all_inactive()
  5345. for obj in self.collection.get_list():
  5346. try:
  5347. # select the object(s) only if it is enabled (plotted)
  5348. if obj.options['plot']:
  5349. # it's a line without area
  5350. if obj.options['xmin'] == obj.options['xmax'] or obj.options['ymin'] == obj.options['ymax']:
  5351. poly_obj = unary_union(obj.solid_geometry).buffer(0.001)
  5352. # it's a geometry with area
  5353. else:
  5354. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5355. (obj.options['xmax'], obj.options['ymin']),
  5356. (obj.options['xmax'], obj.options['ymax']),
  5357. (obj.options['xmin'], obj.options['ymax'])])
  5358. if poly_obj.is_empty or not poly_obj.is_valid:
  5359. continue
  5360. if sel_type is True:
  5361. if poly_obj.within(poly_selection):
  5362. # create the selection box around the selected object
  5363. if self.defaults['global_selection_shape'] is True:
  5364. self.draw_selection_shape(obj)
  5365. self.collection.set_active(obj.options['name'])
  5366. else:
  5367. if poly_selection.intersects(poly_obj):
  5368. # create the selection box around the selected object
  5369. if self.defaults['global_selection_shape'] is True:
  5370. self.draw_selection_shape(obj)
  5371. self.collection.set_active(obj.options['name'])
  5372. obj.selection_shape_drawn = True
  5373. except Exception as e:
  5374. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5375. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5376. # In this case poly_obj creation (see above) will fail
  5377. self.log.debug("App.selection_area_handler() --> %s" % str(e))
  5378. def select_objects(self, key=None):
  5379. """
  5380. Will select objects clicked on canvas
  5381. :param key: for future use in cumulative selection
  5382. :return:
  5383. """
  5384. # list where we store the overlapped objects under our mouse left click position
  5385. if key is None:
  5386. self.objects_under_the_click_list = []
  5387. # Populate the list with the overlapped objects on the click position
  5388. curr_x, curr_y = self.pos
  5389. for obj in self.all_objects_list:
  5390. # ScriptObject and DocumentObject objects can't be selected
  5391. if obj.kind == 'script' or obj.kind == 'document':
  5392. continue
  5393. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5394. continue
  5395. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5396. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5397. if obj.options['name'] not in self.objects_under_the_click_list:
  5398. if obj.options['plot']:
  5399. # add objects to the objects_under_the_click list only if the object is plotted
  5400. # (active and not disabled)
  5401. self.objects_under_the_click_list.append(obj.options['name'])
  5402. try:
  5403. if self.objects_under_the_click_list:
  5404. curr_sel_obj = self.collection.get_active()
  5405. # case when there is only an object under the click and we toggle it
  5406. if len(self.objects_under_the_click_list) == 1:
  5407. if curr_sel_obj is None:
  5408. self.collection.set_active(self.objects_under_the_click_list[0])
  5409. curr_sel_obj = self.collection.get_active()
  5410. # create the selection box around the selected object
  5411. if self.defaults['global_selection_shape'] is True:
  5412. self.draw_selection_shape(curr_sel_obj)
  5413. curr_sel_obj.selection_shape_drawn = True
  5414. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5415. self.collection.on_objects_selection(False)
  5416. self.delete_selection_shape()
  5417. curr_sel_obj.selection_shape_drawn = False
  5418. self.collection.set_active(self.objects_under_the_click_list[0])
  5419. curr_sel_obj = self.collection.get_active()
  5420. # create the selection box around the selected object
  5421. if self.defaults['global_selection_shape'] is True:
  5422. self.draw_selection_shape(curr_sel_obj)
  5423. curr_sel_obj.selection_shape_drawn = True
  5424. self.selected_message(curr_sel_obj=curr_sel_obj)
  5425. elif curr_sel_obj.selection_shape_drawn is False:
  5426. if self.defaults['global_selection_shape'] is True:
  5427. self.draw_selection_shape(curr_sel_obj)
  5428. curr_sel_obj.selection_shape_drawn = True
  5429. else:
  5430. self.collection.on_objects_selection(False)
  5431. self.delete_selection_shape()
  5432. if self.call_source != 'app':
  5433. self.call_source = 'app'
  5434. self.selected_message(curr_sel_obj=curr_sel_obj)
  5435. else:
  5436. # If there is no selected object
  5437. # make active the first element of the overlapped objects list
  5438. if self.collection.get_active() is None:
  5439. self.collection.set_active(self.objects_under_the_click_list[0])
  5440. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5441. name_sel_obj = self.collection.get_active().options['name']
  5442. # In case that there is a selected object but it is not in the overlapped object list
  5443. # make that object inactive and activate the first element in the overlapped object list
  5444. if name_sel_obj not in self.objects_under_the_click_list:
  5445. self.collection.set_inactive(name_sel_obj)
  5446. name_sel_obj = self.objects_under_the_click_list[0]
  5447. self.collection.set_active(name_sel_obj)
  5448. else:
  5449. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5450. self.collection.set_all_inactive()
  5451. self.collection.set_active(
  5452. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5453. curr_sel_obj = self.collection.get_active()
  5454. # delete the possible selection box around a possible selected object
  5455. self.delete_selection_shape()
  5456. curr_sel_obj.selection_shape_drawn = False
  5457. # create the selection box around the selected object
  5458. if self.defaults['global_selection_shape'] is True:
  5459. self.draw_selection_shape(curr_sel_obj)
  5460. curr_sel_obj.selection_shape_drawn = True
  5461. self.selected_message(curr_sel_obj=curr_sel_obj)
  5462. else:
  5463. # deselect everything
  5464. self.collection.on_objects_selection(False)
  5465. # delete the possible selection box around a possible selected object
  5466. self.delete_selection_shape()
  5467. for o in self.collection.get_list():
  5468. o.selection_shape_drawn = False
  5469. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5470. # only when working on App
  5471. if self.call_source == 'app':
  5472. if self.click_noproject is False:
  5473. # if the Tool Tab is in focus don't change focus to Project Tab
  5474. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5475. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5476. else:
  5477. # restore auto open the Project Tab
  5478. self.click_noproject = False
  5479. # delete any text in the status bar, implicitly the last object name that was selected
  5480. # self.inform.emit("")
  5481. else:
  5482. self.call_source = 'app'
  5483. except Exception as e:
  5484. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5485. def selected_message(self, curr_sel_obj):
  5486. if curr_sel_obj:
  5487. if curr_sel_obj.kind == 'gerber':
  5488. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5489. color='green',
  5490. name=str(curr_sel_obj.options['name']),
  5491. tx=_("selected"))
  5492. )
  5493. elif curr_sel_obj.kind == 'excellon':
  5494. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5495. color='brown',
  5496. name=str(curr_sel_obj.options['name']),
  5497. tx=_("selected"))
  5498. )
  5499. elif curr_sel_obj.kind == 'cncjob':
  5500. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5501. color='blue',
  5502. name=str(curr_sel_obj.options['name']),
  5503. tx=_("selected"))
  5504. )
  5505. elif curr_sel_obj.kind == 'geometry':
  5506. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5507. color='red',
  5508. name=str(curr_sel_obj.options['name']),
  5509. tx=_("selected"))
  5510. )
  5511. def delete_hover_shape(self):
  5512. self.hover_shapes.clear()
  5513. self.hover_shapes.redraw()
  5514. def draw_hover_shape(self, sel_obj, color=None):
  5515. """
  5516. :param sel_obj: The object for which the hover shape must be drawn
  5517. :param color: The color of the hover shape
  5518. :return: None
  5519. """
  5520. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5521. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5522. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5523. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5524. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5525. if self.defaults['units'].upper() == 'MM':
  5526. hover_rect = hover_rect.buffer(-0.1)
  5527. hover_rect = hover_rect.buffer(0.2)
  5528. else:
  5529. hover_rect = hover_rect.buffer(-0.00393)
  5530. hover_rect = hover_rect.buffer(0.00787)
  5531. # if color:
  5532. # face = Color(color)
  5533. # face.alpha = 0.2
  5534. # outline = Color(color, alpha=0.8)
  5535. # else:
  5536. # face = Color(self.defaults['global_sel_fill'])
  5537. # face.alpha = 0.2
  5538. # outline = self.defaults['global_sel_line']
  5539. if color:
  5540. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5541. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5542. else:
  5543. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5544. outline = self.defaults['global_sel_line']
  5545. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5546. if self.is_legacy is True:
  5547. self.hover_shapes.redraw()
  5548. def delete_selection_shape(self):
  5549. self.move_tool.sel_shapes.clear()
  5550. self.move_tool.sel_shapes.redraw()
  5551. def draw_selection_shape(self, sel_obj, color=None):
  5552. """
  5553. Will draw a selection shape around the selected object.
  5554. :param sel_obj: The object for which the selection shape must be drawn
  5555. :param color: The color for the selection shape.
  5556. :return: None
  5557. """
  5558. if sel_obj is None:
  5559. return
  5560. # it's a line without area
  5561. if sel_obj.options['xmin'] == sel_obj.options['xmax'] or sel_obj.options['ymin'] == sel_obj.options['ymax']:
  5562. sel_rect = unary_union(sel_obj.solid_geometry).buffer(0.100001)
  5563. # it's a geometry with area
  5564. else:
  5565. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5566. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5567. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5568. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5569. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5570. b_sel_rect = None
  5571. try:
  5572. if self.defaults['units'].upper() == 'MM':
  5573. b_sel_rect = sel_rect.buffer(-0.1)
  5574. b_sel_rect = b_sel_rect.buffer(0.2)
  5575. else:
  5576. b_sel_rect = sel_rect.buffer(-0.00393)
  5577. b_sel_rect = b_sel_rect.buffer(0.00787)
  5578. except Exception:
  5579. pass
  5580. if b_sel_rect.is_empty or not b_sel_rect.is_valid or b_sel_rect is None:
  5581. b_sel_rect = sel_rect
  5582. if color:
  5583. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5584. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5585. else:
  5586. if self.is_legacy is False:
  5587. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5588. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5589. else:
  5590. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5591. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5592. self.sel_objects_list.append(self.move_tool.sel_shapes.add(b_sel_rect,
  5593. color=outline,
  5594. face_color=face,
  5595. update=True,
  5596. layer=0,
  5597. tolerance=None))
  5598. if self.is_legacy is True:
  5599. self.move_tool.sel_shapes.redraw()
  5600. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5601. """
  5602. Will draw a selection shape when dragging mouse on canvas.
  5603. :param old_coords: Old coordinates
  5604. :param coords: New coordinates
  5605. :param kwargs: Keyword arguments
  5606. :return:
  5607. """
  5608. if 'color' in kwargs:
  5609. color = kwargs['color']
  5610. else:
  5611. color = self.defaults['global_sel_line']
  5612. if 'face_color' in kwargs:
  5613. face_color = kwargs['face_color']
  5614. else:
  5615. face_color = self.defaults['global_sel_fill']
  5616. if 'face_alpha' in kwargs:
  5617. face_alpha = kwargs['face_alpha']
  5618. else:
  5619. face_alpha = 0.3
  5620. x0, y0 = old_coords
  5621. x1, y1 = coords
  5622. pt1 = (x0, y0)
  5623. pt2 = (x1, y0)
  5624. pt3 = (x1, y1)
  5625. pt4 = (x0, y1)
  5626. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5627. # color_t = Color(face_color)
  5628. # color_t.alpha = face_alpha
  5629. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5630. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5631. layer=0, tolerance=None)
  5632. if self.is_legacy is True:
  5633. self.move_tool.sel_shapes.redraw()
  5634. def obj_properties(self):
  5635. """
  5636. Will launch the object Properties Tool
  5637. :return:
  5638. """
  5639. self.defaults.report_usage("obj_properties()")
  5640. self.properties_tool.run(toggle=False)
  5641. def on_project_context_save(self):
  5642. """
  5643. Wrapper, will save the object function of it's type
  5644. :return:
  5645. """
  5646. sel_objects = self.collection.get_selected()
  5647. len_objects = len(sel_objects)
  5648. cnt = 0
  5649. if len_objects > 1:
  5650. for o in sel_objects:
  5651. if o.kind == 'cncjob':
  5652. cnt += 1
  5653. if len_objects == cnt:
  5654. # all selected objects are of type CNCJOB therefore we issue a multiple save
  5655. _filter_ = self.defaults['cncjob_save_filters'] + \
  5656. ";;RML1 Files .rol (*.rol);;HPGL Files .plt (*.plt)"
  5657. dir_file_to_save = self.get_last_save_folder() + '/multi_save'
  5658. try:
  5659. filename, _f = FCFileSaveDialog.get_saved_filename(
  5660. caption=_("Export Code ..."),
  5661. directory=dir_file_to_save,
  5662. ext_filter=_filter_
  5663. )
  5664. except TypeError:
  5665. filename, _f = FCFileSaveDialog.get_saved_filename(
  5666. caption=_("Export Code ..."),
  5667. ext_filter=_filter_)
  5668. filename = filename.rpartition('/')[0]
  5669. for ob in sel_objects:
  5670. ob.read_form()
  5671. fname = '%s/%s' % (filename, ob.options['name'])
  5672. ob.export_gcode_handler(fname, is_gcode=True)
  5673. return
  5674. obj = self.collection.get_active()
  5675. if type(obj) == GeometryObject:
  5676. self.on_file_exportdxf()
  5677. elif type(obj) == ExcellonObject:
  5678. self.on_file_saveexcellon()
  5679. elif type(obj) == CNCJobObject:
  5680. obj.on_exportgcode_button_click()
  5681. elif type(obj) == GerberObject:
  5682. self.on_file_savegerber()
  5683. elif type(obj) == ScriptObject:
  5684. self.on_file_savescript()
  5685. elif type(obj) == DocumentObject:
  5686. self.on_file_savedocument()
  5687. def obj_move(self):
  5688. """
  5689. Callback for the Move menu entry in various Context Menu's.
  5690. :return:
  5691. """
  5692. self.defaults.report_usage("obj_move()")
  5693. self.move_tool.run(toggle=False)
  5694. # ###############################################################################################################
  5695. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  5696. # ###############################################################################################################
  5697. def init_code_editor(self, name):
  5698. self.text_editor_tab = AppTextEditor(app=self, plain_text=True)
  5699. # add the tab if it was closed
  5700. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  5701. self.text_editor_tab.setObjectName('text_editor_tab')
  5702. # delete the absolute and relative position and messages in the infobar
  5703. # self.ui.position_label.setText("")
  5704. # self.ui.rel_position_label.setText("")
  5705. # hide coordinates toolbars in the infobar while in DB
  5706. self.ui.coords_toolbar.hide()
  5707. self.ui.delta_coords_toolbar.hide()
  5708. self.toggle_codeeditor = True
  5709. self.text_editor_tab.code_editor.completer_enable = False
  5710. self.text_editor_tab.buttonRun.hide()
  5711. # make sure to keep a reference to the code editor
  5712. self.reference_code_editor = self.text_editor_tab.code_editor
  5713. # Switch plot_area to CNCJob tab
  5714. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  5715. def on_view_source(self):
  5716. """
  5717. Called when the user wants to see the source file of the selected object
  5718. :return:
  5719. """
  5720. try:
  5721. obj = self.collection.get_active()
  5722. except Exception as e:
  5723. self.log.debug("App.on_view_source() --> %s" % str(e))
  5724. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5725. return 'fail'
  5726. if obj is None:
  5727. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5728. return 'fail'
  5729. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  5730. self.proc_container.view.set_busy(_("Loading..."))
  5731. flt = "All Files (*.*)"
  5732. if obj.kind == 'gerber':
  5733. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5734. elif obj.kind == 'excellon':
  5735. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5736. elif obj.kind == 'cncjob':
  5737. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5738. self.source_editor_tab = AppTextEditor(app=self, plain_text=True)
  5739. # add the tab if it was closed
  5740. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  5741. self.source_editor_tab.setObjectName('source_editor_tab')
  5742. # delete the absolute and relative position and messages in the infobar
  5743. # self.ui.position_label.setText("")
  5744. # self.ui.rel_position_label.setText("")
  5745. # hide coordinates toolbars in the infobar while in DB
  5746. self.ui.coords_toolbar.hide()
  5747. self.ui.delta_coords_toolbar.hide()
  5748. self.source_editor_tab.code_editor.completer_enable = False
  5749. self.source_editor_tab.buttonRun.hide()
  5750. # Switch plot_area to CNCJob tab
  5751. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  5752. try:
  5753. self.source_editor_tab.buttonOpen.clicked.disconnect()
  5754. except TypeError:
  5755. pass
  5756. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  5757. try:
  5758. self.source_editor_tab.buttonSave.clicked.disconnect()
  5759. except TypeError:
  5760. pass
  5761. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  5762. # then append the text from GCode to the text editor
  5763. if obj.kind == 'cncjob':
  5764. try:
  5765. file = obj.export_gcode(to_file=True)
  5766. if file == 'fail':
  5767. return 'fail'
  5768. except AttributeError:
  5769. self.inform.emit('[WARNING_NOTCL] %s' %
  5770. _("There is no selected object for which to see it's source file code."))
  5771. return 'fail'
  5772. else:
  5773. try:
  5774. file = StringIO(obj.source_file)
  5775. except (AttributeError, TypeError):
  5776. self.inform.emit('[WARNING_NOTCL] %s' %
  5777. _("There is no selected object for which to see it's source file code."))
  5778. return 'fail'
  5779. self.source_editor_tab.t_frame.hide()
  5780. try:
  5781. self.source_editor_tab.load_text(file.getvalue(), clear_text=True, move_to_start=True)
  5782. except Exception as e:
  5783. self.log.debug('App.on_view_source() -->%s' % str(e))
  5784. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  5785. return
  5786. self.source_editor_tab.t_frame.show()
  5787. self.proc_container.view.set_idle()
  5788. # self.ui.show()
  5789. def on_toggle_code_editor(self):
  5790. self.defaults.report_usage("on_toggle_code_editor()")
  5791. if self.toggle_codeeditor is False:
  5792. self.init_code_editor(name=_("Code Editor"))
  5793. self.text_editor_tab.buttonOpen.clicked.disconnect()
  5794. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  5795. self.text_editor_tab.buttonSave.clicked.disconnect()
  5796. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  5797. else:
  5798. for idx in range(self.ui.plot_tab_area.count()):
  5799. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  5800. self.ui.plot_tab_area.closeTab(idx)
  5801. break
  5802. self.toggle_codeeditor = False
  5803. def on_code_editor_close(self):
  5804. self.toggle_codeeditor = False
  5805. def goto_text_line(self):
  5806. """
  5807. Will scroll a text to the specified text line.
  5808. :return: None
  5809. """
  5810. dia_box = Dialog_box(title=_("Go to Line ..."),
  5811. label=_("Line:"),
  5812. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  5813. initial_text='')
  5814. try:
  5815. line = int(dia_box.location) - 1
  5816. except (ValueError, TypeError):
  5817. line = 0
  5818. if dia_box.ok:
  5819. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  5820. # at the top of the window
  5821. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  5822. # get the document() of the AppTextEditor
  5823. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  5824. # create a Text Cursor based on the searched line
  5825. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  5826. # set cursor of the code editor with the cursor at the searcehd line
  5827. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  5828. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  5829. """
  5830. Re-generates all plots from all objects.
  5831. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  5832. :param muted: if True don't print messages
  5833. :param use_thread: if True will use threading for plotting the objects
  5834. :return: None
  5835. """
  5836. self.log.debug("Plot_all()")
  5837. if muted is not True:
  5838. self.inform[str, bool].emit('%s...' % _("Redrawing all objects"), False)
  5839. for plot_obj in self.collection.get_list():
  5840. def worker_task(obj):
  5841. with self.proc_container.new("Plotting"):
  5842. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  5843. if fit_view is True:
  5844. self.app_obj.object_plotted.emit(obj)
  5845. if use_thread is True:
  5846. # Send to worker
  5847. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  5848. else:
  5849. worker_task(plot_obj)
  5850. def register_folder(self, filename):
  5851. """
  5852. Register the last folder used by the app to open something
  5853. :param filename: the last folder is extracted from the filename
  5854. :return: None
  5855. """
  5856. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  5857. def register_save_folder(self, filename):
  5858. """
  5859. Register the last folder used by the app to save something
  5860. :param filename: the last folder is extracted from the filename
  5861. :return: None
  5862. """
  5863. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  5864. # def set_progress_bar(self, percentage, text=""):
  5865. # """
  5866. # Set a progress bar to a value (percentage)
  5867. #
  5868. # :param percentage: Value set to the progressbar
  5869. # :param text: Not used
  5870. # :return: None
  5871. # """
  5872. # self.ui.progress_bar.setValue(int(percentage))
  5873. def setup_recent_items(self):
  5874. """
  5875. Setup a dictionary with the recent files accessed, organized by type
  5876. :return:
  5877. """
  5878. icons = {
  5879. "gerber": self.resource_location + "/flatcam_icon16.png",
  5880. "excellon": self.resource_location + "/drill16.png",
  5881. 'geometry': self.resource_location + "/geometry16.png",
  5882. "cncjob": self.resource_location + "/cnc16.png",
  5883. "script": self.resource_location + "/script_new24.png",
  5884. "document": self.resource_location + "/notes16_1.png",
  5885. "project": self.resource_location + "/project16.png",
  5886. "svg": self.resource_location + "/geometry16.png",
  5887. "dxf": self.resource_location + "/dxf16.png",
  5888. "pdf": self.resource_location + "/pdf32.png",
  5889. "image": self.resource_location + "/image16.png"
  5890. }
  5891. try:
  5892. image_opener = self.image_tool.import_image
  5893. except AttributeError:
  5894. image_opener = None
  5895. openers = {
  5896. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_gerber, 'params': [fname]}),
  5897. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_excellon, 'params': [fname]}),
  5898. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.import_dxf, 'params': [fname]}),
  5899. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_gcode, 'params': [fname]}),
  5900. "script": lambda fname: self.worker_task.emit({'fcn': self.f_handlers.open_script, 'params': [fname]}),
  5901. "document": None,
  5902. 'project': self.f_handlers.open_project,
  5903. 'svg': self.f_handlers.import_svg,
  5904. 'dxf': self.f_handlers.import_dxf,
  5905. 'image': image_opener,
  5906. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  5907. }
  5908. # Open recent file for files
  5909. try:
  5910. f = open(self.data_path + '/recent.json')
  5911. except IOError:
  5912. App.log.error("Failed to load recent item list.")
  5913. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  5914. return
  5915. try:
  5916. self.recent = json.load(f)
  5917. except json.errors.JSONDecodeError:
  5918. App.log.error("Failed to parse recent item list.")
  5919. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  5920. f.close()
  5921. return
  5922. f.close()
  5923. # Open recent file for projects
  5924. try:
  5925. fp = open(self.data_path + '/recent_projects.json')
  5926. except IOError:
  5927. App.log.error("Failed to load recent project item list.")
  5928. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  5929. return
  5930. try:
  5931. self.recent_projects = json.load(fp)
  5932. except json.errors.JSONDecodeError:
  5933. App.log.error("Failed to parse recent project item list.")
  5934. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  5935. fp.close()
  5936. return
  5937. fp.close()
  5938. # Closure needed to create callbacks in a loop.
  5939. # Otherwise late binding occurs.
  5940. def make_callback(func, fname):
  5941. def opener():
  5942. func(fname)
  5943. return opener
  5944. def reset_recent_files():
  5945. # Reset menu
  5946. self.ui.recent.clear()
  5947. self.recent = []
  5948. try:
  5949. ff = open(self.data_path + '/recent.json', 'w')
  5950. except IOError:
  5951. App.log.error("Failed to open recent items file for writing.")
  5952. return
  5953. json.dump(self.recent, ff)
  5954. def reset_recent_projects():
  5955. # Reset menu
  5956. self.ui.recent_projects.clear()
  5957. self.recent_projects = []
  5958. try:
  5959. frp = open(self.data_path + '/recent_projects.json', 'w')
  5960. except IOError:
  5961. App.log.error("Failed to open recent projects items file for writing.")
  5962. return
  5963. json.dump(self.recent, frp)
  5964. # Reset menu
  5965. self.ui.recent.clear()
  5966. self.ui.recent_projects.clear()
  5967. # Create menu items for projects
  5968. for recent in self.recent_projects:
  5969. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  5970. if recent['kind'] == 'project':
  5971. try:
  5972. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  5973. # Attach callback
  5974. o = make_callback(openers[recent["kind"]], recent['filename'])
  5975. action.triggered.connect(o)
  5976. self.ui.recent_projects.addAction(action)
  5977. except KeyError:
  5978. App.log.error("Unsupported file type: %s" % recent["kind"])
  5979. # Last action in Recent Files menu is one that Clear the content
  5980. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  5981. (_("Clear Recent projects")), self)
  5982. clear_action_proj.triggered.connect(reset_recent_projects)
  5983. self.ui.recent_projects.addSeparator()
  5984. self.ui.recent_projects.addAction(clear_action_proj)
  5985. # Create menu items for files
  5986. for recent in self.recent:
  5987. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  5988. if recent['kind'] != 'project':
  5989. try:
  5990. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  5991. # Attach callback
  5992. o = make_callback(openers[recent["kind"]], recent['filename'])
  5993. action.triggered.connect(o)
  5994. self.ui.recent.addAction(action)
  5995. except KeyError:
  5996. App.log.error("Unsupported file type: %s" % recent["kind"])
  5997. # Last action in Recent Files menu is one that Clear the content
  5998. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  5999. (_("Clear Recent files")), self)
  6000. clear_action.triggered.connect(reset_recent_files)
  6001. self.ui.recent.addSeparator()
  6002. self.ui.recent.addAction(clear_action)
  6003. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  6004. # self.ui.menufilerecent.set_submenu(recent_menu)
  6005. # recent_menu.show_all()
  6006. # self.ui.recent.show()
  6007. self.log.debug("Recent items list has been populated.")
  6008. def on_properties_tab_click(self, index):
  6009. if self.ui.properties_scroll_area.widget().objectName() == 'default_properties':
  6010. self.setup_default_properties_tab()
  6011. def setup_default_properties_tab(self):
  6012. """
  6013. Default text for the Properties tab when is not taken by the Object UI.
  6014. :return:
  6015. """
  6016. # label = QtWidgets.QLabel("Choose an item from Project")
  6017. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  6018. # sel_title = QtWidgets.QTextEdit()
  6019. # sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  6020. # sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  6021. #
  6022. # f_settings = QSettings("Open Source", "FlatCAM")
  6023. # if f_settings.contains("notebook_font_size"):
  6024. # fsize = f_settings.value('notebook_font_size', type=int)
  6025. # else:
  6026. # fsize = 12
  6027. #
  6028. # tsize = fsize + int(fsize / 2)
  6029. #
  6030. # selected_text = ''
  6031. #
  6032. # sel_title.setText(selected_text)
  6033. # sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6034. # Tree Widget
  6035. d_properties_tw = FCTree(columns=2)
  6036. d_properties_tw.setObjectName("default_properties")
  6037. d_properties_tw.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6038. d_properties_tw.setStyleSheet("QTreeWidget {border: 0px;}")
  6039. root = d_properties_tw.invisibleRootItem()
  6040. font = QtGui.QFont()
  6041. font.setBold(True)
  6042. p_color = QtGui.QColor("#000000") if self.defaults['global_gray_icons'] is False else QtGui.QColor("#FFFFFF")
  6043. # main Items categories
  6044. general_cat = d_properties_tw.addParent(root, _('General'), expanded=True, color=p_color, font=font)
  6045. d_properties_tw.addChild(parent=general_cat,
  6046. title=['%s:' % _("Name"), '%s' % _("FlatCAM Evo")], column1=True)
  6047. d_properties_tw.addChild(parent=general_cat,
  6048. title=['%s:' % _("Version"), '%s' % str(self.version)], column1=True)
  6049. d_properties_tw.addChild(parent=general_cat,
  6050. title=['%s:' % _("Release date"), '%s' % str(self.version_date)], column1=True)
  6051. grid_cat = d_properties_tw.addParent(root, _('Grid'), expanded=True, color=p_color, font=font)
  6052. d_properties_tw.addChild(parent=grid_cat,
  6053. title=['%s:' % _("Displayed"), '%s' % str(self.defaults['global_grid_lines'])],
  6054. column1=True)
  6055. d_properties_tw.addChild(parent=grid_cat,
  6056. title=['%s:' % _("Snap"), '%s' % str(self.defaults['global_grid_snap'])],
  6057. column1=True)
  6058. d_properties_tw.addChild(parent=grid_cat,
  6059. title=['%s:' % _("X value"), '%s' % str(self.ui.grid_gap_x_entry.get_value())],
  6060. column1=True)
  6061. d_properties_tw.addChild(parent=grid_cat,
  6062. title=['%s:' % _("Y value"), '%s' % str(self.ui.grid_gap_y_entry.get_value())],
  6063. column1=True)
  6064. canvas_cat = d_properties_tw.addParent(root, _('Canvas'), expanded=True, color=p_color, font=font)
  6065. d_properties_tw.addChild(parent=canvas_cat,
  6066. title=['%s:' % _("Axis"), '%s' % str(self.defaults['global_axis'])],
  6067. column1=True)
  6068. d_properties_tw.addChild(parent=canvas_cat,
  6069. title=['%s:' % _("Workspace active"),
  6070. '%s' % str(self.defaults['global_workspace'])],
  6071. column1=True)
  6072. d_properties_tw.addChild(parent=canvas_cat,
  6073. title=['%s:' % _("Workspace size"),
  6074. '%s' % str(self.defaults['global_workspaceT'])],
  6075. column1=True)
  6076. d_properties_tw.addChild(parent=canvas_cat,
  6077. title=['%s:' % _("Workspace orientation"),
  6078. '%s' % _("Portrait") if self.defaults[
  6079. 'global_workspace_orientation'] == 'p' else
  6080. _("Landscape")],
  6081. column1=True)
  6082. d_properties_tw.addChild(parent=canvas_cat,
  6083. title=['%s:' % _("HUD"), '%s' % str(self.defaults['global_hud'])],
  6084. column1=True)
  6085. self.ui.properties_scroll_area.setWidget(d_properties_tw)
  6086. def setup_obj_classes(self):
  6087. """
  6088. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  6089. class.
  6090. :return: None
  6091. """
  6092. FlatCAMObj.app = self
  6093. ObjectCollection.app = self
  6094. Gerber.app = self
  6095. Excellon.app = self
  6096. Geometry.app = self
  6097. CNCjob.app = self
  6098. FCProcess.app = self
  6099. FCProcessContainer.app = self
  6100. OptionsGroupUI.app = self
  6101. def version_check(self):
  6102. """
  6103. Checks for the latest version of the program. Alerts the
  6104. user if theirs is outdated. This method is meant to be run
  6105. in a separate thread.
  6106. :return: None
  6107. """
  6108. self.log.debug("version_check()")
  6109. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  6110. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  6111. App.version_url,
  6112. str(self.defaults['global_serial']),
  6113. str(self.version),
  6114. str(self.os),
  6115. urllib.parse.urlencode(self.defaults["global_stats"])
  6116. )
  6117. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  6118. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  6119. # urllib.parse.urlencode(self.defaults["global_stats"])
  6120. else:
  6121. # no_stats dict; just so it won't break things on website
  6122. no_ststs_dict = {}
  6123. no_ststs_dict["global_ststs"] = {}
  6124. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  6125. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  6126. self.log.debug("Checking for updates @ %s" % full_url)
  6127. # ## Get the data
  6128. try:
  6129. f = urllib.request.urlopen(full_url)
  6130. except Exception:
  6131. # App.log.warning("Failed checking for latest version. Could not connect.")
  6132. self.log.warning("Failed checking for latest version. Could not connect.")
  6133. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  6134. return
  6135. try:
  6136. data = json.load(f)
  6137. except Exception as e:
  6138. App.log.error("Could not parse information about latest version.")
  6139. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  6140. self.log.debug("json.load(): %s" % str(e))
  6141. f.close()
  6142. return
  6143. f.close()
  6144. # ## Latest version?
  6145. if self.version >= data["version"]:
  6146. self.log.debug("FlatCAM is up to date!")
  6147. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  6148. return
  6149. self.log.debug("Newer version available.")
  6150. self.message.emit(
  6151. _("Newer Version Available"),
  6152. '%s<br><br>><b>%s</b><br>%s' % (
  6153. _("There is a newer version of FlatCAM available for download:"),
  6154. str(data["name"]),
  6155. str(data["message"])
  6156. ),
  6157. _("info")
  6158. )
  6159. def on_plotcanvas_setup(self, container=None):
  6160. """
  6161. This is doing the setup for the plot area (canvas).
  6162. :param container: QT Widget where to install the canvas
  6163. :return: None
  6164. """
  6165. if container:
  6166. plot_container = container
  6167. else:
  6168. plot_container = self.ui.right_layout
  6169. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  6170. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  6171. self.is_legacy = True
  6172. self.defaults["global_graphic_engine"] = "2D"
  6173. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  6174. else:
  6175. try:
  6176. self.plotcanvas = PlotCanvas(plot_container, self)
  6177. except Exception as er:
  6178. msg_txt = traceback.format_exc()
  6179. self.log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  6180. self.log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  6181. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  6182. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  6183. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  6184. msg += msg_txt
  6185. self.inform.emit(msg)
  6186. return 'fail'
  6187. # So it can receive key presses
  6188. self.plotcanvas.native.setFocus()
  6189. if self.is_legacy is False:
  6190. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  6191. # Set the mouse button for panning
  6192. self.plotcanvas.view.camera.pan_button_setting = pan_button
  6193. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  6194. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  6195. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  6196. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  6197. # Keys over plot enabled
  6198. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  6199. if self.defaults['global_cursor_type'] == 'small':
  6200. self.app_cursor = self.plotcanvas.new_cursor()
  6201. else:
  6202. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  6203. if self.ui.grid_snap_btn.isChecked():
  6204. self.app_cursor.enabled = True
  6205. else:
  6206. self.app_cursor.enabled = False
  6207. if self.is_legacy is False:
  6208. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  6209. else:
  6210. # will use the default Matplotlib axes
  6211. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  6212. def on_zoom_fit(self):
  6213. """
  6214. Callback for zoom-fit request. This can be either from the corresponding
  6215. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  6216. with axes limits from the geometry bounds of all objects.
  6217. :return: None
  6218. """
  6219. if self.is_legacy is False:
  6220. self.plotcanvas.fit_view()
  6221. else:
  6222. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  6223. width = xmax - xmin
  6224. height = ymax - ymin
  6225. xmin -= 0.05 * width
  6226. xmax += 0.05 * width
  6227. ymin -= 0.05 * height
  6228. ymax += 0.05 * height
  6229. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  6230. def on_zoom_in(self):
  6231. """
  6232. Callback for zoom-in request.
  6233. :return:
  6234. """
  6235. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  6236. def on_zoom_out(self):
  6237. """
  6238. Callback for zoom-out request.
  6239. :return:
  6240. """
  6241. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  6242. def disable_all_plots(self):
  6243. self.defaults.report_usage("disable_all_plots()")
  6244. self.disable_plots(self.collection.get_list())
  6245. self.inform.emit('[success] %s' % _("All plots disabled."))
  6246. def disable_other_plots(self):
  6247. self.defaults.report_usage("disable_other_plots()")
  6248. self.disable_plots(self.collection.get_non_selected())
  6249. self.inform.emit('[success] %s' % _("All non selected plots disabled."))
  6250. def enable_all_plots(self):
  6251. self.defaults.report_usage("enable_all_plots()")
  6252. self.enable_plots(self.collection.get_list())
  6253. self.inform.emit('[success] %s' % _("All plots enabled."))
  6254. def enable_other_plots(self):
  6255. self.defaults.report_usage("enable_other_plots()")
  6256. self.enable_plots(self.collection.get_non_selected())
  6257. self.inform.emit('[success] %s' % _("All non selected plots enabled."))
  6258. def on_enable_sel_plots(self):
  6259. self.log.debug("App.on_enable_sel_plot()")
  6260. object_list = self.collection.get_selected()
  6261. self.enable_plots(objects=object_list)
  6262. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  6263. def on_disable_sel_plots(self):
  6264. self.log.debug("App.on_disable_sel_plot()")
  6265. # self.inform.emit(_("Disabling plots ..."))
  6266. object_list = self.collection.get_selected()
  6267. self.disable_plots(objects=object_list)
  6268. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  6269. def enable_plots(self, objects):
  6270. """
  6271. Enable plots
  6272. :param objects: list of Objects to be enabled
  6273. :return:
  6274. """
  6275. self.log.debug("Enabling plots ...")
  6276. # self.inform.emit(_("Working ..."))
  6277. for obj in objects:
  6278. if obj.options['plot'] is False:
  6279. obj.options.set_change_callback(lambda x: None)
  6280. obj.options['plot'] = True
  6281. try:
  6282. # only the Gerber obj has on_plot_cb_click() method
  6283. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  6284. # disable this cb while disconnected,
  6285. # in case the operation takes time the user is not allowed to change it
  6286. obj.ui.plot_cb.setDisabled(True)
  6287. except AttributeError:
  6288. pass
  6289. obj.set_form_item("plot")
  6290. try:
  6291. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  6292. obj.ui.plot_cb.setDisabled(False)
  6293. except AttributeError:
  6294. pass
  6295. obj.options.set_change_callback(obj.on_options_change)
  6296. self.collection.update_view()
  6297. def worker_task(objs):
  6298. with self.proc_container.new(_("Enabling plots ...")):
  6299. for plot_obj in objs:
  6300. # obj.options['plot'] = True
  6301. if isinstance(plot_obj, CNCJobObject):
  6302. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  6303. else:
  6304. plot_obj.plot(visible=True)
  6305. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  6306. def disable_plots(self, objects):
  6307. """
  6308. Disables plots
  6309. :param objects: list of Objects to be disabled
  6310. :return:
  6311. """
  6312. self.log.debug("Disabling plots ...")
  6313. # self.inform.emit(_("Working ..."))
  6314. for obj in objects:
  6315. if obj.options['plot'] is True:
  6316. obj.options.set_change_callback(lambda x: None)
  6317. obj.options['plot'] = False
  6318. try:
  6319. # only the Gerber obj has on_plot_cb_click() method
  6320. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  6321. obj.ui.plot_cb.setDisabled(True)
  6322. except AttributeError:
  6323. pass
  6324. obj.set_form_item("plot")
  6325. try:
  6326. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  6327. obj.ui.plot_cb.setDisabled(False)
  6328. except AttributeError:
  6329. pass
  6330. obj.options.set_change_callback(obj.on_options_change)
  6331. try:
  6332. self.delete_selection_shape()
  6333. except Exception as e:
  6334. self.log.debug("App.disable_plots() --> %s" % str(e))
  6335. self.collection.update_view()
  6336. def worker_task(objs):
  6337. with self.proc_container.new(_("Disabling plots ...")):
  6338. for plot_obj in objs:
  6339. # obj.options['plot'] = True
  6340. if isinstance(plot_obj, CNCJobObject):
  6341. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  6342. else:
  6343. plot_obj.plot(visible=False)
  6344. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  6345. def toggle_plots(self, objects):
  6346. """
  6347. Toggle plots visibility
  6348. :param objects: list of Objects for which to be toggled the visibility
  6349. :return: None
  6350. """
  6351. # if no objects selected then do nothing
  6352. if not self.collection.get_selected():
  6353. return
  6354. self.log.debug("Toggling plots ...")
  6355. self.inform.emit(_("Working ..."))
  6356. for obj in objects:
  6357. if obj.options['plot'] is False:
  6358. obj.options['plot'] = True
  6359. else:
  6360. obj.options['plot'] = False
  6361. self.app_obj.plots_updated.emit()
  6362. def clear_plots(self):
  6363. """
  6364. Clear the plots
  6365. :return: None
  6366. """
  6367. objects = self.collection.get_list()
  6368. for obj in objects:
  6369. obj.clear(obj == objects[-1])
  6370. # Clear pool to free memory
  6371. self.clear_pool()
  6372. def on_set_color_action_triggered(self):
  6373. """
  6374. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  6375. :return:
  6376. """
  6377. new_color = self.defaults['gerber_plot_fill']
  6378. clicked_action = self.sender()
  6379. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  6380. act_name = clicked_action.text()
  6381. sel_obj_list = self.collection.get_selected()
  6382. if not sel_obj_list:
  6383. return
  6384. # a default value, I just chose this one
  6385. alpha_level = 'BF'
  6386. for sel_obj in sel_obj_list:
  6387. if sel_obj.kind == 'excellon':
  6388. alpha_level = str(hex(
  6389. self.ui.excellon_defaults_form.excellon_gen_group.excellon_alpha_entry.get_value())[2:])
  6390. elif sel_obj.kind == 'gerber':
  6391. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.gerber_alpha_entry.get_value())[2:])
  6392. elif sel_obj.kind == 'geometry':
  6393. alpha_level = 'FF'
  6394. else:
  6395. self.log.debug(
  6396. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  6397. continue
  6398. sel_obj.alpha_level = alpha_level
  6399. if act_name == _('Red'):
  6400. new_color = '#FF0000' + alpha_level
  6401. if act_name == _('Blue'):
  6402. new_color = '#0000FF' + alpha_level
  6403. if act_name == _('Yellow'):
  6404. new_color = '#FFDF00' + alpha_level
  6405. if act_name == _('Green'):
  6406. new_color = '#00FF00' + alpha_level
  6407. if act_name == _('Purple'):
  6408. new_color = '#FF00FF' + alpha_level
  6409. if act_name == _('Brown'):
  6410. new_color = '#A52A2A' + alpha_level
  6411. if act_name == _('White'):
  6412. new_color = '#FFFFFF' + alpha_level
  6413. if act_name == _('Black'):
  6414. new_color = '#000000' + alpha_level
  6415. if act_name == _('Custom'):
  6416. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  6417. c_dialog = QtWidgets.QColorDialog()
  6418. plot_fill_color = c_dialog.getColor(initial=new_color)
  6419. if plot_fill_color.isValid() is False:
  6420. return
  6421. new_color = str(plot_fill_color.name()) + alpha_level
  6422. if act_name == _("Default"):
  6423. for sel_obj in sel_obj_list:
  6424. if sel_obj.kind == 'excellon':
  6425. new_color = self.defaults['excellon_plot_fill']
  6426. new_line_color = self.defaults['excellon_plot_line']
  6427. elif sel_obj.kind == 'gerber':
  6428. new_color = self.defaults['gerber_plot_fill']
  6429. new_line_color = self.defaults['gerber_plot_line']
  6430. elif sel_obj.kind == 'geometry':
  6431. new_color = self.defaults['geometry_plot_line']
  6432. new_line_color = self.defaults['geometry_plot_line']
  6433. else:
  6434. self.log.debug(
  6435. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  6436. continue
  6437. sel_obj.fill_color = new_color
  6438. sel_obj.outline_color = new_line_color
  6439. sel_obj.shapes.redraw(
  6440. update_colors=(new_color, new_line_color)
  6441. )
  6442. return
  6443. if act_name == _("Opacity"):
  6444. # alpha_level, ok_button = QtWidgets.QInputDialog.getInt(self.ui, _("Set alpha level ..."),
  6445. # '%s:' % _("Value"),
  6446. # min=0, max=255, step=1, value=191)
  6447. alpha_dialog = FCInputDialogSlider(
  6448. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, init_val=191)
  6449. alpha_level, ok_button = alpha_dialog.get_results()
  6450. if ok_button:
  6451. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  6452. for sel_obj in sel_obj_list:
  6453. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  6454. sel_obj.shapes.redraw(
  6455. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  6456. )
  6457. return
  6458. new_line_color = color_variant(new_color[:7], 0.7)
  6459. if act_name == _("White"):
  6460. new_line_color = color_variant("#dedede", 0.7)
  6461. for sel_obj in sel_obj_list:
  6462. sel_obj.fill_color = new_color
  6463. sel_obj.outline_color = new_line_color
  6464. sel_obj.shapes.redraw(
  6465. update_colors=(new_color, new_line_color)
  6466. )
  6467. # make sure to set the color in the Gerber colors storage self.defaults["gerber_color_list"]
  6468. group = self.collection.group_items["gerber"]
  6469. group_index = self.collection.index(group.row(), 0, QtCore.QModelIndex())
  6470. new_c = (new_line_color, new_color)
  6471. for sel_obj in sel_obj_list:
  6472. if sel_obj.kind == 'gerber':
  6473. item = sel_obj.item
  6474. item_index = self.collection.index(item.row(), 0, group_index)
  6475. idx = item_index.row()
  6476. self.defaults["gerber_color_list"][idx] = new_c
  6477. def generate_cnc_job(self, objects):
  6478. """
  6479. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  6480. :param objects: Selected objects in the Project Tab
  6481. :return:
  6482. """
  6483. self.defaults.report_usage("generate_cnc_job()")
  6484. # for obj in objects:
  6485. # obj.generatecncjob()
  6486. for obj in objects:
  6487. obj.on_generatecnc_button_click()
  6488. def start_delayed_quit(self, delay, filename, should_quit=None):
  6489. """
  6490. :param delay: period of checking if project file size is more than zero; in seconds
  6491. :param filename: the name of the project file to be checked periodically for size more than zero
  6492. :param should_quit: if the task finished will be followed by an app quit; boolean
  6493. :return:
  6494. """
  6495. to_quit = should_quit
  6496. self.save_timer = QtCore.QTimer()
  6497. self.save_timer.setInterval(delay)
  6498. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  6499. self.save_timer.start()
  6500. def check_project_file_size(self, filename, should_quit=None):
  6501. """
  6502. :param filename: the name of the project file to be checked periodically for size more than zero
  6503. :param should_quit: will quit the app if True; boolean
  6504. :return:
  6505. """
  6506. try:
  6507. if os.stat(filename).st_size > 0:
  6508. self.save_in_progress = False
  6509. self.save_timer.stop()
  6510. if should_quit:
  6511. self.app_quit.emit()
  6512. except Exception:
  6513. traceback.print_exc()
  6514. def save_project_auto(self):
  6515. """
  6516. Called periodically to save the project.
  6517. It will save if there is no block on the save, if the project was saved at least once and if there is no save in
  6518. # progress.
  6519. :return:
  6520. """
  6521. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  6522. self.on_file_saveproject()
  6523. def save_project_auto_update(self):
  6524. """
  6525. Update the auto save time interval value.
  6526. :return:
  6527. """
  6528. self.log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  6529. try:
  6530. if self.autosave_timer.isActive():
  6531. self.autosave_timer.stop()
  6532. except Exception:
  6533. pass
  6534. if self.defaults['global_autosave'] is True:
  6535. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  6536. self.autosave_timer.start()
  6537. def on_options_app2project(self):
  6538. """
  6539. Callback for Options->Transfer Options->App=>Project. Copies options
  6540. from application defaults to project defaults.
  6541. :return: None
  6542. """
  6543. self.defaults.report_usage("on_options_app2project")
  6544. self.preferencesUiManager.defaults_read_form()
  6545. self.options.update(self.defaults)
  6546. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False, new_line=True):
  6547. """
  6548. Shows a message on the FlatCAM Shell
  6549. :param msg: Message to display.
  6550. :param show: Opens the shell.
  6551. :param error: Shows the message as an error.
  6552. :param warning: Shows the message as an warning.
  6553. :param success: Shows the message as an success.
  6554. :param selected: Indicate that something was selected on canvas
  6555. :return: None
  6556. """
  6557. end = '\n' if new_line is True else ''
  6558. if show:
  6559. self.ui.shell_dock.show()
  6560. try:
  6561. if error:
  6562. self.shell.append_error(msg + end)
  6563. elif warning:
  6564. self.shell.append_warning(msg + end)
  6565. elif success:
  6566. self.shell.append_success(msg + end)
  6567. elif selected:
  6568. self.shell.append_selected(msg + end)
  6569. else:
  6570. self.shell.append_output(msg + end)
  6571. except AttributeError:
  6572. self.log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  6573. def dec_format(self, val, dec=None):
  6574. """
  6575. Returns a formatted float value with a certain number of decimals
  6576. """
  6577. dec_nr = dec if dec is not None else self.decimals
  6578. return float('%.*f' % (dec_nr, val))
  6579. class ArgsThread(QtCore.QObject):
  6580. open_signal = pyqtSignal(list)
  6581. start = pyqtSignal()
  6582. stop = pyqtSignal()
  6583. if sys.platform == 'win32':
  6584. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  6585. else:
  6586. address = ('/tmp/testipc', 'AF_UNIX')
  6587. def __init__(self):
  6588. super().__init__()
  6589. self.listener = None
  6590. self.thread_exit = False
  6591. self.start.connect(self.run)
  6592. self.stop.connect(self.close_listener)
  6593. def my_loop(self, address):
  6594. try:
  6595. self.listener = Listener(*address)
  6596. while self.thread_exit is False:
  6597. conn = self.listener.accept()
  6598. self.serve(conn)
  6599. except socket.error:
  6600. try:
  6601. conn = Client(*address)
  6602. conn.send(sys.argv)
  6603. conn.send('close')
  6604. # close the current instance only if there are args
  6605. if len(sys.argv) > 1:
  6606. try:
  6607. self.listener.close()
  6608. except Exception:
  6609. pass
  6610. sys.exit()
  6611. except ConnectionRefusedError:
  6612. if sys.platform == 'win32':
  6613. pass
  6614. else:
  6615. os.system('rm /tmp/testipc')
  6616. self.listener = Listener(*address)
  6617. while True:
  6618. conn = self.listener.accept()
  6619. self.serve(conn)
  6620. def serve(self, conn):
  6621. while self.thread_exit is False:
  6622. msg = conn.recv()
  6623. if msg == 'close':
  6624. break
  6625. self.open_signal.emit(msg)
  6626. conn.close()
  6627. # the decorator is a must; without it this technique will not work unless the start signal is connected
  6628. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  6629. @pyqtSlot()
  6630. def run(self):
  6631. self.my_loop(self.address)
  6632. @pyqtSlot()
  6633. def close_listener(self):
  6634. self.thread_exit = True
  6635. self.listener.close()
  6636. class MenuFileHandlers(QtCore.QObject):
  6637. def __init__(self, app):
  6638. super().__init__()
  6639. self.app = app
  6640. self.inform = self.app.inform
  6641. self.splash = self.app.splash
  6642. self.worker_task = self.app.worker_task
  6643. self.defaults = self.app.defaults
  6644. self.pagesize = {}
  6645. def on_fileopengerber(self, signal, name=None):
  6646. """
  6647. File menu callback for opening a Gerber.
  6648. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6649. :param name:
  6650. :return: None
  6651. """
  6652. self.app.log.debug("on_fileopengerber()")
  6653. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 " \
  6654. "*.gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb " \
  6655. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.outline);;" \
  6656. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko " \
  6657. "*.outline);;" \
  6658. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6659. "*.mil);;" \
  6660. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6661. "Allegro Files (*.art);;" \
  6662. "Mentor Files (*.pho *.gdo);;" \
  6663. "All Files (*.*)"
  6664. if name is None:
  6665. try:
  6666. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6667. directory=self.app.get_last_folder(),
  6668. filter=_filter_,
  6669. initialFilter=self.app.last_op_gerber_filter)
  6670. except TypeError:
  6671. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6672. filenames = [str(filename) for filename in filenames]
  6673. self.app.last_op_gerber_filter = _f
  6674. else:
  6675. filenames = [name]
  6676. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6677. "Canvas initialization finished in"),
  6678. '%.2f' % self.app.used_time,
  6679. _("Opening Gerber file.")),
  6680. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6681. color=QtGui.QColor("gray"))
  6682. if len(filenames) == 0:
  6683. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6684. else:
  6685. for filename in filenames:
  6686. if filename != '':
  6687. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6688. def on_fileopenexcellon(self, signal, name=None):
  6689. """
  6690. File menu callback for opening an Excellon file.
  6691. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6692. :param name:
  6693. :return: None
  6694. """
  6695. self.app.log.debug("on_fileopenexcellon()")
  6696. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6697. "All Files (*.*)"
  6698. if name is None:
  6699. try:
  6700. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6701. directory=self.app.get_last_folder(),
  6702. filter=_filter_,
  6703. initialFilter=self.app.last_op_excellon_filter)
  6704. except TypeError:
  6705. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6706. filenames = [str(filename) for filename in filenames]
  6707. self.app.last_op_excellon_filter = _f
  6708. else:
  6709. filenames = [str(name)]
  6710. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6711. "Canvas initialization finished in"),
  6712. '%.2f' % self.app.used_time,
  6713. _("Opening Excellon file.")),
  6714. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6715. color=QtGui.QColor("gray"))
  6716. if len(filenames) == 0:
  6717. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6718. else:
  6719. for filename in filenames:
  6720. if filename != '':
  6721. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6722. def on_fileopengcode(self, signal, name=None):
  6723. """
  6724. File menu call back for opening gcode.
  6725. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6726. :param name:
  6727. :return:
  6728. """
  6729. self.app.log.debug("on_fileopengcode()")
  6730. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6731. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6732. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6733. "All Files (*.*)"
  6734. if name is None:
  6735. try:
  6736. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6737. directory=self.app.get_last_folder(),
  6738. filter=_filter_,
  6739. initialFilter=self.app.last_op_gcode_filter)
  6740. except TypeError:
  6741. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6742. filenames = [str(filename) for filename in filenames]
  6743. self.app.last_op_gcode_filter = _f
  6744. else:
  6745. filenames = [name]
  6746. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6747. "Canvas initialization finished in"),
  6748. '%.2f' % self.app.used_time,
  6749. _("Opening G-Code file.")),
  6750. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6751. color=QtGui.QColor("gray"))
  6752. if len(filenames) == 0:
  6753. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6754. else:
  6755. for filename in filenames:
  6756. if filename != '':
  6757. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6758. def on_file_openproject(self, signal):
  6759. """
  6760. File menu callback for opening a project.
  6761. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6762. :return: None
  6763. """
  6764. self.app.log.debug("on_file_openproject()")
  6765. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6766. try:
  6767. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6768. directory=self.app.get_last_folder(), filter=_filter_)
  6769. except TypeError:
  6770. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6771. filename = str(filename)
  6772. if filename == "":
  6773. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6774. else:
  6775. # self.worker_task.emit({'fcn': self.open_project,
  6776. # 'params': [filename]})
  6777. # The above was failing because open_project() is not
  6778. # thread safe. The new_project()
  6779. self.open_project(filename)
  6780. def on_fileopenhpgl2(self, signal, name=None):
  6781. """
  6782. File menu callback for opening a HPGL2.
  6783. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6784. :param name:
  6785. :return: None
  6786. """
  6787. self.app.log.debug("on_fileopenhpgl2()")
  6788. _filter_ = "HPGL2 Files (*.plt);;" \
  6789. "All Files (*.*)"
  6790. if name is None:
  6791. try:
  6792. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6793. directory=self.app.get_last_folder(),
  6794. filter=_filter_)
  6795. except TypeError:
  6796. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6797. filenames = [str(filename) for filename in filenames]
  6798. else:
  6799. filenames = [name]
  6800. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6801. "Canvas initialization finished in"),
  6802. '%.2f' % self.app.used_time,
  6803. _("Opening HPGL2 file.")),
  6804. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6805. color=QtGui.QColor("gray"))
  6806. if len(filenames) == 0:
  6807. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6808. else:
  6809. for filename in filenames:
  6810. if filename != '':
  6811. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6812. def on_file_openconfig(self, signal):
  6813. """
  6814. File menu callback for opening a config file.
  6815. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6816. :return: None
  6817. """
  6818. self.app.log.debug("on_file_openconfig()")
  6819. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6820. try:
  6821. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6822. directory=self.app.data_path, filter=_filter_)
  6823. except TypeError:
  6824. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6825. filter=_filter_)
  6826. if filename == "":
  6827. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6828. else:
  6829. self.open_config_file(filename)
  6830. def on_file_exportsvg(self):
  6831. """
  6832. Callback for menu item File->Export SVG.
  6833. :return: None
  6834. """
  6835. self.app.log.debug("on_file_exportsvg()")
  6836. obj = self.app.collection.get_active()
  6837. if obj is None:
  6838. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6839. msg = _("Please Select a Geometry object to export")
  6840. msgbox = QtWidgets.QMessageBox()
  6841. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6842. msgbox.setInformativeText(msg)
  6843. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6844. msgbox.setDefaultButton(bt_ok)
  6845. msgbox.exec_()
  6846. return
  6847. # Check for more compatible types and add as required
  6848. if (not isinstance(obj, GeometryObject)
  6849. and not isinstance(obj, GerberObject)
  6850. and not isinstance(obj, CNCJobObject)
  6851. and not isinstance(obj, ExcellonObject)):
  6852. msg = '[ERROR_NOTCL] %s' % _("Only Geometry, Gerber and CNCJob objects can be used.")
  6853. msgbox = QtWidgets.QMessageBox()
  6854. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6855. msgbox.setInformativeText(msg)
  6856. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6857. msgbox.setDefaultButton(bt_ok)
  6858. msgbox.exec_()
  6859. return
  6860. name = obj.options["name"]
  6861. _filter = "SVG File (*.svg);;All Files (*.*)"
  6862. try:
  6863. filename, _f = FCFileSaveDialog.get_saved_filename(
  6864. caption=_("Export SVG"),
  6865. directory=self.app.get_last_save_folder() + '/' + str(name) + '_svg',
  6866. ext_filter=_filter)
  6867. except TypeError:
  6868. filename, _f = FCFileSaveDialog.get_saved_filename(
  6869. caption=_("Export SVG"),
  6870. ext_filter=_filter)
  6871. filename = str(filename)
  6872. if filename == "":
  6873. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6874. return
  6875. else:
  6876. self.export_svg(name, filename)
  6877. if self.defaults["global_open_style"] is False:
  6878. self.app.file_opened.emit("SVG", filename)
  6879. self.app.file_saved.emit("SVG", filename)
  6880. def on_file_exportpng(self):
  6881. self.app.log.debug("on_file_exportpng()")
  6882. date = str(datetime.today()).rpartition('.')[0]
  6883. date = ''.join(c for c in date if c not in ':-')
  6884. date = date.replace(' ', '_')
  6885. data = None
  6886. if self.app.is_legacy is False:
  6887. image = _screenshot(alpha=False)
  6888. data = np.asarray(image)
  6889. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6890. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6891. return
  6892. filter_ = "PNG File (*.png);;All Files (*.*)"
  6893. try:
  6894. filename, _f = FCFileSaveDialog.get_saved_filename(
  6895. caption=_("Export PNG Image"),
  6896. directory=self.app.get_last_save_folder() + '/png_' + date,
  6897. ext_filter=filter_)
  6898. except TypeError:
  6899. filename, _f = FCFileSaveDialog.get_saved_filename(
  6900. caption=_("Export PNG Image"),
  6901. ext_filter=filter_)
  6902. filename = str(filename)
  6903. if filename == "":
  6904. self.inform.emit(_("Cancelled."))
  6905. return
  6906. else:
  6907. if self.app.is_legacy is False:
  6908. write_png(filename, data)
  6909. else:
  6910. self.app.plotcanvas.figure.savefig(filename)
  6911. if self.defaults["global_open_style"] is False:
  6912. self.app.file_opened.emit("png", filename)
  6913. self.app.file_saved.emit("png", filename)
  6914. def on_file_savegerber(self):
  6915. """
  6916. Callback for menu item in Project context menu.
  6917. :return: None
  6918. """
  6919. self.app.log.debug("on_file_savegerber()")
  6920. obj = self.app.collection.get_active()
  6921. if obj is None:
  6922. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6923. return
  6924. # Check for more compatible types and add as required
  6925. if not isinstance(obj, GerberObject):
  6926. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6927. return
  6928. name = self.app.collection.get_active().options["name"]
  6929. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6930. try:
  6931. filename, _f = FCFileSaveDialog.get_saved_filename(
  6932. caption="Save Gerber source file",
  6933. directory=self.app.get_last_save_folder() + '/' + name,
  6934. ext_filter=_filter)
  6935. except TypeError:
  6936. filename, _f = FCFileSaveDialog.get_saved_filename(
  6937. caption=_("Save Gerber source file"),
  6938. ext_filter=_filter)
  6939. filename = str(filename)
  6940. if filename == "":
  6941. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6942. return
  6943. else:
  6944. self.save_source_file(name, filename)
  6945. if self.defaults["global_open_style"] is False:
  6946. self.app.file_opened.emit("Gerber", filename)
  6947. self.app.file_saved.emit("Gerber", filename)
  6948. def on_file_savescript(self):
  6949. """
  6950. Callback for menu item in Project context menu.
  6951. :return: None
  6952. """
  6953. self.app.log.debug("on_file_savescript()")
  6954. obj = self.app.collection.get_active()
  6955. if obj is None:
  6956. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6957. return
  6958. # Check for more compatible types and add as required
  6959. if not isinstance(obj, ScriptObject):
  6960. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6961. return
  6962. name = self.app.collection.get_active().options["name"]
  6963. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6964. try:
  6965. filename, _f = FCFileSaveDialog.get_saved_filename(
  6966. caption="Save Script source file",
  6967. directory=self.app.get_last_save_folder() + '/' + name,
  6968. ext_filter=_filter)
  6969. except TypeError:
  6970. filename, _f = FCFileSaveDialog.get_saved_filename(
  6971. caption=_("Save Script source file"),
  6972. ext_filter=_filter)
  6973. filename = str(filename)
  6974. if filename == "":
  6975. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6976. return
  6977. else:
  6978. self.save_source_file(name, filename)
  6979. if self.defaults["global_open_style"] is False:
  6980. self.app.file_opened.emit("Script", filename)
  6981. self.app.file_saved.emit("Script", filename)
  6982. def on_file_savedocument(self):
  6983. """
  6984. Callback for menu item in Project context menu.
  6985. :return: None
  6986. """
  6987. self.app.log.debug("on_file_savedocument()")
  6988. obj = self.app.collection.get_active()
  6989. if obj is None:
  6990. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6991. return
  6992. # Check for more compatible types and add as required
  6993. if not isinstance(obj, ScriptObject):
  6994. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6995. return
  6996. name = self.app.collection.get_active().options["name"]
  6997. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6998. try:
  6999. filename, _f = FCFileSaveDialog.get_saved_filename(
  7000. caption="Save Document source file",
  7001. directory=self.app.get_last_save_folder() + '/' + name,
  7002. ext_filter=_filter)
  7003. except TypeError:
  7004. filename, _f = FCFileSaveDialog.get_saved_filename(
  7005. caption=_("Save Document source file"),
  7006. ext_filter=_filter)
  7007. filename = str(filename)
  7008. if filename == "":
  7009. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7010. return
  7011. else:
  7012. self.save_source_file(name, filename)
  7013. if self.defaults["global_open_style"] is False:
  7014. self.app.file_opened.emit("Document", filename)
  7015. self.app.file_saved.emit("Document", filename)
  7016. def on_file_saveexcellon(self):
  7017. """
  7018. Callback for menu item in project context menu.
  7019. :return: None
  7020. """
  7021. self.app.log.debug("on_file_saveexcellon()")
  7022. obj = self.app.collection.get_active()
  7023. if obj is None:
  7024. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7025. return
  7026. # Check for more compatible types and add as required
  7027. if not isinstance(obj, ExcellonObject):
  7028. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7029. return
  7030. name = self.app.collection.get_active().options["name"]
  7031. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7032. try:
  7033. filename, _f = FCFileSaveDialog.get_saved_filename(
  7034. caption=_("Save Excellon source file"),
  7035. directory=self.app.get_last_save_folder() + '/' + name,
  7036. ext_filter=_filter)
  7037. except TypeError:
  7038. filename, _f = FCFileSaveDialog.get_saved_filename(
  7039. caption=_("Save Excellon source file"), ext_filter=_filter)
  7040. filename = str(filename)
  7041. if filename == "":
  7042. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7043. return
  7044. else:
  7045. self.save_source_file(name, filename)
  7046. if self.defaults["global_open_style"] is False:
  7047. self.app.file_opened.emit("Excellon", filename)
  7048. self.app.file_saved.emit("Excellon", filename)
  7049. def on_file_exportexcellon(self):
  7050. """
  7051. Callback for menu item File->Export->Excellon.
  7052. :return: None
  7053. """
  7054. self.app.log.debug("on_file_exportexcellon()")
  7055. obj = self.app.collection.get_active()
  7056. if obj is None:
  7057. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7058. return
  7059. # Check for more compatible types and add as required
  7060. if not isinstance(obj, ExcellonObject):
  7061. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7062. return
  7063. name = self.app.collection.get_active().options["name"]
  7064. _filter = self.defaults["excellon_save_filters"]
  7065. try:
  7066. filename, _f = FCFileSaveDialog.get_saved_filename(
  7067. caption=_("Export Excellon"),
  7068. directory=self.app.get_last_save_folder() + '/' + name,
  7069. ext_filter=_filter)
  7070. except TypeError:
  7071. filename, _f = FCFileSaveDialog.get_saved_filename(
  7072. caption=_("Export Excellon"),
  7073. ext_filter=_filter)
  7074. filename = str(filename)
  7075. if filename == "":
  7076. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7077. return
  7078. else:
  7079. used_extension = filename.rpartition('.')[2]
  7080. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  7081. self.export_excellon(name, filename)
  7082. if self.defaults["global_open_style"] is False:
  7083. self.app.file_opened.emit("Excellon", filename)
  7084. self.app.file_saved.emit("Excellon", filename)
  7085. def on_file_exportgerber(self):
  7086. """
  7087. Callback for menu item File->Export->Gerber.
  7088. :return: None
  7089. """
  7090. App.log.debug("on_file_exportgerber()")
  7091. obj = self.app.collection.get_active()
  7092. if obj is None:
  7093. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7094. return
  7095. # Check for more compatible types and add as required
  7096. if not isinstance(obj, GerberObject):
  7097. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7098. return
  7099. name = self.app.collection.get_active().options["name"]
  7100. _filter_ = self.defaults['gerber_save_filters']
  7101. try:
  7102. filename, _f = FCFileSaveDialog.get_saved_filename(
  7103. caption=_("Export Gerber"),
  7104. directory=self.app.get_last_save_folder() + '/' + name,
  7105. ext_filter=_filter_)
  7106. except TypeError:
  7107. filename, _f = FCFileSaveDialog.get_saved_filename(
  7108. caption=_("Export Gerber"),
  7109. ext_filter=_filter_)
  7110. filename = str(filename)
  7111. if filename == "":
  7112. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7113. return
  7114. else:
  7115. used_extension = filename.rpartition('.')[2]
  7116. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  7117. self.export_gerber(name, filename)
  7118. if self.defaults["global_open_style"] is False:
  7119. self.app.file_opened.emit("Gerber", filename)
  7120. self.app.file_saved.emit("Gerber", filename)
  7121. def on_file_exportdxf(self):
  7122. """
  7123. Callback for menu item File->Export DXF.
  7124. :return: None
  7125. """
  7126. App.log.debug("on_file_exportdxf()")
  7127. obj = self.app.collection.get_active()
  7128. if obj is None:
  7129. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  7130. msg = _("Please Select a Geometry object to export")
  7131. msgbox = QtWidgets.QMessageBox()
  7132. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  7133. msgbox.setInformativeText(msg)
  7134. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7135. msgbox.setDefaultButton(bt_ok)
  7136. msgbox.exec_()
  7137. return
  7138. # Check for more compatible types and add as required
  7139. if not isinstance(obj, GeometryObject):
  7140. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  7141. msgbox = QtWidgets.QMessageBox()
  7142. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  7143. msgbox.setInformativeText(msg)
  7144. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7145. msgbox.setDefaultButton(bt_ok)
  7146. msgbox.exec_()
  7147. return
  7148. name = self.app.collection.get_active().options["name"]
  7149. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  7150. try:
  7151. filename, _f = FCFileSaveDialog.get_saved_filename(
  7152. caption=_("Export DXF"),
  7153. directory=self.app.get_last_save_folder() + '/' + name,
  7154. ext_filter=_filter_)
  7155. except TypeError:
  7156. filename, _f = FCFileSaveDialog.get_saved_filename(
  7157. caption=_("Export DXF"),
  7158. ext_filter=_filter_)
  7159. filename = str(filename)
  7160. if filename == "":
  7161. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7162. return
  7163. else:
  7164. self.export_dxf(name, filename)
  7165. if self.defaults["global_open_style"] is False:
  7166. self.app.file_opened.emit("DXF", filename)
  7167. self.app.file_saved.emit("DXF", filename)
  7168. def on_file_importsvg(self, type_of_obj):
  7169. """
  7170. Callback for menu item File->Import SVG.
  7171. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7172. :type type_of_obj: str
  7173. :return: None
  7174. """
  7175. self.app.log.debug("on_file_importsvg()")
  7176. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  7177. try:
  7178. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7179. directory=self.app.get_last_folder(),
  7180. filter=_filter_)
  7181. except TypeError:
  7182. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7183. filter=_filter_)
  7184. if type_of_obj != "geometry" and type_of_obj != "gerber":
  7185. type_of_obj = "geometry"
  7186. filenames = [str(filename) for filename in filenames]
  7187. if len(filenames) == 0:
  7188. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7189. else:
  7190. for filename in filenames:
  7191. if filename != '':
  7192. self.worker_task.emit({'fcn': self.import_svg, 'params': [filename, type_of_obj]})
  7193. def on_file_importdxf(self, type_of_obj):
  7194. """
  7195. Callback for menu item File->Import DXF.
  7196. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7197. :type type_of_obj: str
  7198. :return: None
  7199. """
  7200. self.app.log.debug("on_file_importdxf()")
  7201. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  7202. try:
  7203. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7204. directory=self.app.get_last_folder(),
  7205. filter=_filter_)
  7206. except TypeError:
  7207. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7208. filter=_filter_)
  7209. if type_of_obj != "geometry" and type_of_obj != "gerber":
  7210. type_of_obj = "geometry"
  7211. filenames = [str(filename) for filename in filenames]
  7212. if len(filenames) == 0:
  7213. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7214. else:
  7215. for filename in filenames:
  7216. if filename != '':
  7217. self.worker_task.emit({'fcn': self.import_dxf, 'params': [filename, type_of_obj]})
  7218. def on_file_new_click(self):
  7219. """
  7220. Callback for menu item File -> New.
  7221. Executed on clicking the Menu -> File -> New Project
  7222. :return:
  7223. """
  7224. if self.app.collection.get_list() and self.app.should_we_save:
  7225. msgbox = QtWidgets.QMessageBox()
  7226. # msgbox.setText("<B>Save changes ...</B>")
  7227. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7228. "Creating a New project will delete them.\n"
  7229. "Do you want to Save the project?"))
  7230. msgbox.setWindowTitle(_("Save changes"))
  7231. msgbox.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/save_as.png'))
  7232. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  7233. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7234. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7235. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7236. msgbox.setDefaultButton(bt_yes)
  7237. msgbox.exec_()
  7238. response = msgbox.clickedButton()
  7239. if response == bt_yes:
  7240. self.on_file_saveprojectas()
  7241. elif response == bt_cancel:
  7242. return
  7243. elif response == bt_no:
  7244. self.on_file_new()
  7245. else:
  7246. self.on_file_new()
  7247. self.inform.emit('[success] %s...' % _("New Project created"))
  7248. def on_file_new(self, cli=None):
  7249. """
  7250. Returns the application to its startup state. This method is thread-safe.
  7251. :param cli: Boolean. If True this method was run from command line
  7252. :return: None
  7253. """
  7254. self.defaults.report_usage("on_file_new")
  7255. # Remove everything from memory
  7256. self.app.log.debug("on_file_new()")
  7257. # close any editor that might be open
  7258. if self.app.call_source != 'app':
  7259. self.app.editor2object(cleanup=True)
  7260. # ## EDITOR section
  7261. self.app.geo_editor = AppGeoEditor(self.app)
  7262. self.app.exc_editor = AppExcEditor(self.app)
  7263. self.app.grb_editor = AppGerberEditor(self.app)
  7264. # Clear pool
  7265. self.app.clear_pool()
  7266. for obj in self.app.collection.get_list():
  7267. # delete shapes left drawn from mark shape_collections, if any
  7268. if isinstance(obj, GerberObject):
  7269. try:
  7270. obj.mark_shapes_storage.clear()
  7271. obj.mark_shapes.clear(update=True)
  7272. obj.mark_shapes.enabled = False
  7273. except AttributeError:
  7274. pass
  7275. # also delete annotation shapes, if any
  7276. elif isinstance(obj, CNCJobObject):
  7277. try:
  7278. obj.text_col.enabled = False
  7279. del obj.text_col
  7280. obj.annotation.clear(update=True)
  7281. del obj.annotation
  7282. except AttributeError:
  7283. pass
  7284. # delete the exclusion areas
  7285. self.app.exc_areas.clear_shapes()
  7286. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7287. self.app.shell.init_tcl()
  7288. # delete any selection shape on canvas
  7289. self.app.delete_selection_shape()
  7290. # delete all FlatCAM objects
  7291. self.app.collection.delete_all()
  7292. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  7293. self.app.setup_default_properties_tab()
  7294. # Clear project filename
  7295. self.app.project_filename = None
  7296. # Load the application defaults
  7297. self.defaults.load(filename=os.path.join(self.app.data_path, 'current_defaults.FlatConfig'), inform=self.inform)
  7298. # Re-fresh project options
  7299. self.app.on_options_app2project()
  7300. # Init FlatCAMTools
  7301. self.app.init_tools()
  7302. # Try to close all tabs in the PlotArea but only if the appGUI is active (CLI is None)
  7303. if cli is None:
  7304. # we need to go in reverse because once we remove a tab then the index changes
  7305. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  7306. # and so on. Therefore the deletion should be done in reverse
  7307. wdg_count = self.app.ui.plot_tab_area.tabBar.count() - 1
  7308. for index in range(wdg_count, -1, -1):
  7309. try:
  7310. self.app.ui.plot_tab_area.closeTab(index)
  7311. except Exception as e:
  7312. log.debug("App.on_file_new() --> %s" % str(e))
  7313. # # And then add again the Plot Area
  7314. self.app.ui.plot_tab_area.insertTab(0, self.app.ui.plot_tab, _("Plot Area"))
  7315. self.app.ui.plot_tab_area.protectTab(0)
  7316. # take the focus of the Notebook on Project Tab.
  7317. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  7318. self.app.ui.set_ui_title(name=_("New Project - Not saved"))
  7319. def on_filenewscript(self, silent=False):
  7320. """
  7321. Will create a new script file and open it in the Code Editor
  7322. :param silent: if True will not display status messages
  7323. :return: None
  7324. """
  7325. if silent is False:
  7326. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  7327. # hide coordinates toolbars in the infobar while in DB
  7328. self.app.ui.coords_toolbar.hide()
  7329. self.app.ui.delta_coords_toolbar.hide()
  7330. self.app.app_obj.new_script_object()
  7331. def on_fileopenscript(self, name=None, silent=False):
  7332. """
  7333. Will open a Tcl script file into the Code Editor
  7334. :param silent: if True will not display status messages
  7335. :param name: name of a Tcl script file to open
  7336. :return: None
  7337. """
  7338. self.app.log.debug("on_fileopenscript()")
  7339. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7340. "All Files (*.*)"
  7341. if name:
  7342. filenames = [name]
  7343. else:
  7344. try:
  7345. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7346. caption=_("Open TCL script"), directory=self.app.get_last_folder(), filter=_filter_)
  7347. except TypeError:
  7348. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7349. if len(filenames) == 0:
  7350. if silent is False:
  7351. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7352. else:
  7353. for filename in filenames:
  7354. if filename != '':
  7355. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7356. def on_fileopenscript_example(self, name=None, silent=False):
  7357. """
  7358. Will open a Tcl script file into the Code Editor
  7359. :param silent: if True will not display status messages
  7360. :param name: name of a Tcl script file to open
  7361. :return:
  7362. """
  7363. self.app.log.debug("on_fileopenscript_example()")
  7364. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7365. "All Files (*.*)"
  7366. # test if the app was frozen and choose the path for the configuration file
  7367. if getattr(sys, "frozen", False) is True:
  7368. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  7369. else:
  7370. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  7371. if name:
  7372. filenames = [name]
  7373. else:
  7374. try:
  7375. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  7376. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  7377. except TypeError:
  7378. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  7379. if len(filenames) == 0:
  7380. if silent is False:
  7381. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7382. else:
  7383. for filename in filenames:
  7384. if filename != '':
  7385. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  7386. def on_filerunscript(self, name=None, silent=False):
  7387. """
  7388. File menu callback for loading and running a TCL script.
  7389. :param silent: if True will not display status messages
  7390. :param name: name of a Tcl script file to be run by FlatCAM
  7391. :return: None
  7392. """
  7393. self.app.log.debug("on_file_runscript()")
  7394. if name:
  7395. filename = name
  7396. if self.app.cmd_line_headless != 1:
  7397. self.splash.showMessage('%s: %ssec\n%s' %
  7398. (_("Canvas initialization started.\n"
  7399. "Canvas initialization finished in"), '%.2f' % self.app.used_time,
  7400. _("Executing ScriptObject file.")
  7401. ),
  7402. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7403. color=QtGui.QColor("gray"))
  7404. else:
  7405. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  7406. "All Files (*.*)"
  7407. try:
  7408. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7409. directory=self.app.get_last_folder(),
  7410. filter=_filter_)
  7411. except TypeError:
  7412. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7413. # The Qt methods above will return a QString which can cause problems later.
  7414. # So far json.dump() will fail to serialize it.
  7415. filename = str(filename)
  7416. if filename == "":
  7417. if silent is False:
  7418. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7419. else:
  7420. if self.app.cmd_line_headless != 1:
  7421. if self.app.ui.shell_dock.isHidden():
  7422. self.app.ui.shell_dock.show()
  7423. try:
  7424. with open(filename, "r") as tcl_script:
  7425. cmd_line_shellfile_content = tcl_script.read()
  7426. if self.app.cmd_line_headless != 1:
  7427. self.app.shell.exec_command(cmd_line_shellfile_content)
  7428. else:
  7429. self.app.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7430. if silent is False:
  7431. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  7432. except Exception as e:
  7433. self.app.debug("App.on_filerunscript() -> %s" % str(e))
  7434. sys.exit(2)
  7435. def on_file_saveproject(self, silent=False):
  7436. """
  7437. Callback for menu item File->Save Project. Saves the project to
  7438. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7439. if set to None. The project is saved by calling ``self.save_project()``.
  7440. :param silent: if True will not display status messages
  7441. :return: None
  7442. """
  7443. if self.app.project_filename is None:
  7444. self.on_file_saveprojectas()
  7445. else:
  7446. self.worker_task.emit({'fcn': self.save_project, 'params': [self.app.project_filename, silent]})
  7447. if self.defaults["global_open_style"] is False:
  7448. self.app.file_opened.emit("project", self.project_filename)
  7449. self.app.file_saved.emit("project", self.project_filename)
  7450. self.app.ui.set_ui_title(name=self.app.project_filename)
  7451. self.app.should_we_save = False
  7452. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7453. """
  7454. Callback for menu item File->Save Project As... Opens a file
  7455. chooser and saves the project to the given file via
  7456. ``self.save_project()``.
  7457. :param make_copy if to be create a copy of the project; boolean
  7458. :param use_thread: if to be run in a separate thread; boolean
  7459. :param quit_action: if to be followed by quiting the application; boolean
  7460. :return: None
  7461. """
  7462. date = str(datetime.today()).rpartition('.')[0]
  7463. date = ''.join(c for c in date if c not in ':-')
  7464. date = date.replace(' ', '_')
  7465. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  7466. try:
  7467. filename, _f = FCFileSaveDialog.get_saved_filename(
  7468. caption=_("Save Project As ..."),
  7469. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.app.get_last_save_folder()), date=date,
  7470. proj=_("Project")),
  7471. ext_filter=filter_
  7472. )
  7473. except TypeError:
  7474. filename, _f = FCFileSaveDialog.get_saved_filename(
  7475. caption=_("Save Project As ..."),
  7476. ext_filter=filter_)
  7477. filename = str(filename)
  7478. if filename == '':
  7479. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7480. return
  7481. if use_thread is True:
  7482. self.worker_task.emit({'fcn': self.save_project, 'params': [filename, quit_action]})
  7483. else:
  7484. self.save_project(filename, quit_action)
  7485. # self.save_project(filename)
  7486. if self.defaults["global_open_style"] is False:
  7487. self.app.file_opened.emit("project", filename)
  7488. self.app.file_saved.emit("project", filename)
  7489. if not make_copy:
  7490. self.app.project_filename = filename
  7491. self.app.ui.set_ui_title(name=self.app.project_filename)
  7492. self.app.should_we_save = False
  7493. def on_file_save_objects_pdf(self, use_thread=True):
  7494. date = str(datetime.today()).rpartition('.')[0]
  7495. date = ''.join(c for c in date if c not in ':-')
  7496. date = date.replace(' ', '_')
  7497. try:
  7498. obj_selection = self.app.collection.get_selected()
  7499. if len(obj_selection) == 1:
  7500. obj_name = str(obj_selection[0].options['name'])
  7501. else:
  7502. obj_name = _("FlatCAM objects print")
  7503. except AttributeError as err:
  7504. self.app.log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7505. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7506. return
  7507. if not obj_selection:
  7508. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7509. return
  7510. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7511. try:
  7512. filename, _f = FCFileSaveDialog.get_saved_filename(
  7513. caption=_("Save Object as PDF ..."),
  7514. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.app.get_last_save_folder()),
  7515. obj_name=obj_name,
  7516. date=date),
  7517. ext_filter=filter_
  7518. )
  7519. except TypeError:
  7520. filename, _f = FCFileSaveDialog.get_saved_filename(
  7521. caption=_("Save Object as PDF ..."),
  7522. ext_filter=filter_)
  7523. filename = str(filename)
  7524. if filename == '':
  7525. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7526. return
  7527. if use_thread is True:
  7528. self.app.proc_container.new(_("Printing PDF ... Please wait."))
  7529. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7530. else:
  7531. self.save_pdf(filename, obj_selection)
  7532. # self.save_project(filename)
  7533. if self.defaults["global_open_style"] is False:
  7534. self.app.file_opened.emit("pdf", filename)
  7535. self.app.file_saved.emit("pdf", filename)
  7536. def save_pdf(self, file_name, obj_selection):
  7537. p_size = self.defaults['global_workspaceT']
  7538. orientation = self.defaults['global_workspace_orientation']
  7539. color = 'black'
  7540. transparency_level = 1.0
  7541. self.pagesize.update(
  7542. {
  7543. 'Bounds': None,
  7544. 'A0': (841 * mm, 1189 * mm),
  7545. 'A1': (594 * mm, 841 * mm),
  7546. 'A2': (420 * mm, 594 * mm),
  7547. 'A3': (297 * mm, 420 * mm),
  7548. 'A4': (210 * mm, 297 * mm),
  7549. 'A5': (148 * mm, 210 * mm),
  7550. 'A6': (105 * mm, 148 * mm),
  7551. 'A7': (74 * mm, 105 * mm),
  7552. 'A8': (52 * mm, 74 * mm),
  7553. 'A9': (37 * mm, 52 * mm),
  7554. 'A10': (26 * mm, 37 * mm),
  7555. 'B0': (1000 * mm, 1414 * mm),
  7556. 'B1': (707 * mm, 1000 * mm),
  7557. 'B2': (500 * mm, 707 * mm),
  7558. 'B3': (353 * mm, 500 * mm),
  7559. 'B4': (250 * mm, 353 * mm),
  7560. 'B5': (176 * mm, 250 * mm),
  7561. 'B6': (125 * mm, 176 * mm),
  7562. 'B7': (88 * mm, 125 * mm),
  7563. 'B8': (62 * mm, 88 * mm),
  7564. 'B9': (44 * mm, 62 * mm),
  7565. 'B10': (31 * mm, 44 * mm),
  7566. 'C0': (917 * mm, 1297 * mm),
  7567. 'C1': (648 * mm, 917 * mm),
  7568. 'C2': (458 * mm, 648 * mm),
  7569. 'C3': (324 * mm, 458 * mm),
  7570. 'C4': (229 * mm, 324 * mm),
  7571. 'C5': (162 * mm, 229 * mm),
  7572. 'C6': (114 * mm, 162 * mm),
  7573. 'C7': (81 * mm, 114 * mm),
  7574. 'C8': (57 * mm, 81 * mm),
  7575. 'C9': (40 * mm, 57 * mm),
  7576. 'C10': (28 * mm, 40 * mm),
  7577. # American paper sizes
  7578. 'LETTER': (8.5 * inch, 11 * inch),
  7579. 'LEGAL': (8.5 * inch, 14 * inch),
  7580. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7581. # From https://en.wikipedia.org/wiki/Paper_size
  7582. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7583. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7584. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7585. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7586. 'LEDGER': (17 * inch, 11 * inch),
  7587. }
  7588. )
  7589. exported_svg = []
  7590. for obj in obj_selection:
  7591. svg_obj = obj.export_svg(scale_stroke_factor=0.0, scale_factor_x=None, scale_factor_y=None,
  7592. skew_factor_x=None, skew_factor_y=None, mirror=None)
  7593. if obj.kind.lower() == 'gerber' or obj.kind.lower() == 'excellon':
  7594. color = obj.fill_color[:-2]
  7595. transparency_level = obj.fill_color[-2:]
  7596. elif obj.kind.lower() == 'geometry':
  7597. color = self.defaults["global_draw_color"]
  7598. # Change the attributes of the exported SVG
  7599. # We don't need stroke-width
  7600. # We set opacity to maximum
  7601. # We set the colour to WHITE
  7602. root = ET.fromstring(svg_obj)
  7603. for child in root:
  7604. child.set('fill', str(color))
  7605. child.set('opacity', str(transparency_level))
  7606. child.set('stroke', str(color))
  7607. exported_svg.append(ET.tostring(root))
  7608. xmin = Inf
  7609. ymin = Inf
  7610. xmax = -Inf
  7611. ymax = -Inf
  7612. for obj in obj_selection:
  7613. try:
  7614. gxmin, gymin, gxmax, gymax = obj.bounds()
  7615. xmin = min([xmin, gxmin])
  7616. ymin = min([ymin, gymin])
  7617. xmax = max([xmax, gxmax])
  7618. ymax = max([ymax, gymax])
  7619. except Exception as e:
  7620. self.app.log.warning(
  7621. "DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7622. # Determine bounding area for svg export
  7623. bounds = [xmin, ymin, xmax, ymax]
  7624. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7625. # This contain the measure units
  7626. uom = obj_selection[0].units.lower()
  7627. # Define a boundary around SVG of about 1.0mm (~39mils)
  7628. if uom in "mm":
  7629. boundary = 1.0
  7630. else:
  7631. boundary = 0.0393701
  7632. # Convert everything to strings for use in the xml doc
  7633. svgwidth = str(size[0] + (2 * boundary))
  7634. svgheight = str(size[1] + (2 * boundary))
  7635. minx = str(bounds[0] - boundary)
  7636. miny = str(bounds[1] + boundary + size[1])
  7637. # Add a SVG Header and footer to the svg output from shapely
  7638. # The transform flips the Y Axis so that everything renders
  7639. # properly within svg apps such as inkscape
  7640. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7641. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7642. svg_header += 'width="' + svgwidth + uom + '" '
  7643. svg_header += 'height="' + svgheight + uom + '" '
  7644. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7645. svg_header += '>'
  7646. svg_header += '<g transform="scale(1,-1)">'
  7647. svg_footer = '</g> </svg>'
  7648. svg_elem = str(svg_header)
  7649. for svg_item in exported_svg:
  7650. svg_elem += str(svg_item)
  7651. svg_elem += str(svg_footer)
  7652. # Parse the xml through a xml parser just to add line feeds
  7653. # and to make it look more pretty for the output
  7654. doc = parse_xml_string(svg_elem)
  7655. doc_final = doc.toprettyxml()
  7656. try:
  7657. if self.defaults['units'].upper() == 'IN':
  7658. unit = inch
  7659. else:
  7660. unit = mm
  7661. doc_final = StringIO(doc_final)
  7662. drawing = svg2rlg(doc_final)
  7663. if p_size == 'Bounds':
  7664. renderPDF.drawToFile(drawing, file_name)
  7665. else:
  7666. if orientation == 'p':
  7667. page_size = portrait(self.pagesize[p_size])
  7668. else:
  7669. page_size = landscape(self.pagesize[p_size])
  7670. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7671. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7672. renderPDF.draw(drawing, my_canvas, 0, 0)
  7673. my_canvas.save()
  7674. except Exception as e:
  7675. self.app.log.debug("MenuFileHandlers.save_pdf() --> PDF output --> %s" % str(e))
  7676. return 'fail'
  7677. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7678. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7679. """
  7680. Exports a Geometry Object to an SVG file.
  7681. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7682. :param filename: Path to the SVG file to save to.
  7683. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7684. :return:
  7685. """
  7686. if filename is None:
  7687. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7688. is not None else self.defaults["global_last_folder"]
  7689. self.app.log.debug("export_svg()")
  7690. try:
  7691. obj = self.app.collection.get_by_name(str(obj_name))
  7692. except Exception:
  7693. return 'fail'
  7694. with self.app.proc_container.new(_("Exporting SVG")):
  7695. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7696. # Determine bounding area for svg export
  7697. bounds = obj.bounds()
  7698. size = obj.size()
  7699. # Convert everything to strings for use in the xml doc
  7700. svgwidth = str(size[0])
  7701. svgheight = str(size[1])
  7702. minx = str(bounds[0])
  7703. miny = str(bounds[1] - size[1])
  7704. uom = obj.units.lower()
  7705. # Add a SVG Header and footer to the svg output from shapely
  7706. # The transform flips the Y Axis so that everything renders
  7707. # properly within svg apps such as inkscape
  7708. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7709. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7710. svg_header += 'width="' + svgwidth + uom + '" '
  7711. svg_header += 'height="' + svgheight + uom + '" '
  7712. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7713. svg_header += '<g transform="scale(1,-1)">'
  7714. svg_footer = '</g> </svg>'
  7715. svg_elem = svg_header + exported_svg + svg_footer
  7716. # Parse the xml through a xml parser just to add line feeds
  7717. # and to make it look more pretty for the output
  7718. svgcode = parse_xml_string(svg_elem)
  7719. svgcode = svgcode.toprettyxml()
  7720. try:
  7721. with open(filename, 'w') as fp:
  7722. fp.write(svgcode)
  7723. except PermissionError:
  7724. self.inform.emit('[WARNING] %s' %
  7725. _("Permission denied, saving not possible.\n"
  7726. "Most likely another app is holding the file open and not accessible."))
  7727. return 'fail'
  7728. if self.defaults["global_open_style"] is False:
  7729. self.app.file_opened.emit("SVG", filename)
  7730. self.app.file_saved.emit("SVG", filename)
  7731. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7732. def on_import_preferences(self):
  7733. """
  7734. Loads the application default settings from a saved file into
  7735. ``self.defaults`` dictionary.
  7736. :return: None
  7737. """
  7738. self.app.log.debug("App.on_import_preferences()")
  7739. # Show file chooser
  7740. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  7741. try:
  7742. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  7743. directory=self.app.data_path,
  7744. filter=filter_)
  7745. except TypeError:
  7746. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  7747. filter=filter_)
  7748. filename = str(filename)
  7749. if filename == "":
  7750. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7751. return
  7752. # Load in the defaults from the chosen file
  7753. self.defaults.load(filename=filename, inform=self.inform)
  7754. self.app.preferencesUiManager.on_preferences_edited()
  7755. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  7756. def on_export_preferences(self):
  7757. """
  7758. Save the defaults dictionary to a file.
  7759. :return: None
  7760. """
  7761. self.app.log.debug("on_export_preferences()")
  7762. # defaults_file_content = None
  7763. # Show file chooser
  7764. date = str(datetime.today()).rpartition('.')[0]
  7765. date = ''.join(c for c in date if c not in ':-')
  7766. date = date.replace(' ', '_')
  7767. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  7768. try:
  7769. filename, _f = FCFileSaveDialog.get_saved_filename(
  7770. caption=_("Export FlatCAM Preferences"),
  7771. directory=self.app.data_path + '/preferences_' + date,
  7772. ext_filter=filter__
  7773. )
  7774. except TypeError:
  7775. filename, _f = FCFileSaveDialog.get_saved_filename(
  7776. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  7777. filename = str(filename)
  7778. if filename == "":
  7779. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7780. return 'fail'
  7781. # Update options
  7782. self.app.preferencesUiManager.defaults_read_form()
  7783. self.defaults.propagate_defaults()
  7784. # Save update options
  7785. try:
  7786. self.defaults.write(filename=filename)
  7787. except Exception:
  7788. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  7789. return
  7790. if self.defaults["global_open_style"] is False:
  7791. self.app.file_opened.emit("preferences", filename)
  7792. self.app.file_saved.emit("preferences", filename)
  7793. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  7794. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7795. """
  7796. Exports a Excellon Object to an Excellon file.
  7797. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7798. :param filename: Path to the Excellon file to save to.
  7799. :param local_use:
  7800. :param use_thread: if to be run in a separate thread
  7801. :return:
  7802. """
  7803. if filename is None:
  7804. if self.defaults["global_last_save_folder"]:
  7805. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7806. else:
  7807. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7808. self.app.log.debug("export_excellon()")
  7809. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7810. self.defaults["excellon_exp_decimals"]
  7811. )
  7812. if local_use is None:
  7813. try:
  7814. obj = self.app.collection.get_by_name(str(obj_name))
  7815. except Exception:
  7816. return "Could not retrieve object: %s" % obj_name
  7817. else:
  7818. obj = local_use
  7819. if not isinstance(obj, ExcellonObject):
  7820. self.inform.emit('[ERROR_NOTCL] %s' %
  7821. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7822. return
  7823. # updated units
  7824. eunits = self.defaults["excellon_exp_units"]
  7825. ewhole = self.defaults["excellon_exp_integer"]
  7826. efract = self.defaults["excellon_exp_decimals"]
  7827. ezeros = self.defaults["excellon_exp_zeros"]
  7828. eformat = self.defaults["excellon_exp_format"]
  7829. slot_type = self.defaults["excellon_exp_slot_type"]
  7830. fc_units = self.defaults['units'].upper()
  7831. if fc_units == 'MM':
  7832. factor = 1 if eunits == 'METRIC' else 0.03937
  7833. else:
  7834. factor = 25.4 if eunits == 'METRIC' else 1
  7835. def make_excellon():
  7836. try:
  7837. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7838. header = 'M48\n'
  7839. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7840. (str(self.app.version), str(self.app.version_date))
  7841. header += ';Filename: %s' % str(obj_name) + '\n'
  7842. header += ';Created on : %s' % time_str + '\n'
  7843. if eformat == 'dec':
  7844. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7845. header += eunits + '\n'
  7846. for tool in obj.tools:
  7847. if eunits == 'METRIC':
  7848. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  7849. tool=str(tool),
  7850. dec=2)
  7851. else:
  7852. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  7853. tool=str(tool),
  7854. dec=4)
  7855. else:
  7856. if ezeros == 'LZ':
  7857. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7858. form='ndec', e_zeros='LZ', factor=factor,
  7859. slot_type=slot_type)
  7860. header += '%s,%s\n' % (eunits, 'LZ')
  7861. header += format_exc
  7862. for tool in obj.tools:
  7863. if eunits == 'METRIC':
  7864. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7865. float(obj.tools[tool]['tooldia']) * factor,
  7866. tool=str(tool),
  7867. dec=2)
  7868. else:
  7869. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7870. float(obj.tools[tool]['tooldia']) * factor,
  7871. tool=str(tool),
  7872. dec=4)
  7873. else:
  7874. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7875. form='ndec', e_zeros='TZ', factor=factor,
  7876. slot_type=slot_type)
  7877. header += '%s,%s\n' % (eunits, 'TZ')
  7878. header += format_exc
  7879. for tool in obj.tools:
  7880. if eunits == 'METRIC':
  7881. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7882. float(obj.tools[tool]['tooldia']) * factor,
  7883. tool=str(tool),
  7884. dec=2)
  7885. else:
  7886. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  7887. float(obj.tools[tool]['tooldia']) * factor,
  7888. tool=str(tool),
  7889. dec=4)
  7890. header += '%\n'
  7891. footer = 'M30\n'
  7892. exported_excellon = header
  7893. exported_excellon += excellon_code
  7894. exported_excellon += footer
  7895. if local_use is None:
  7896. try:
  7897. with open(filename, 'w') as fp:
  7898. fp.write(exported_excellon)
  7899. except PermissionError:
  7900. self.inform.emit('[WARNING] %s' %
  7901. _("Permission denied, saving not possible.\n"
  7902. "Most likely another app is holding the file open and not accessible."))
  7903. return 'fail'
  7904. if self.defaults["global_open_style"] is False:
  7905. self.app.file_opened.emit("Excellon", filename)
  7906. self.app.file_saved.emit("Excellon", filename)
  7907. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7908. else:
  7909. return exported_excellon
  7910. except Exception as e:
  7911. self.app.log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7912. return 'fail'
  7913. if use_thread is True:
  7914. with self.app.proc_container.new(_("Exporting Excellon")):
  7915. def job_thread_exc(app_obj):
  7916. ret = make_excellon()
  7917. if ret == 'fail':
  7918. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7919. return
  7920. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7921. else:
  7922. eret = make_excellon()
  7923. if eret == 'fail':
  7924. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7925. return 'fail'
  7926. if local_use is not None:
  7927. return eret
  7928. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7929. """
  7930. Exports a Gerber Object to an Gerber file.
  7931. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7932. :param filename: Path to the Gerber file to save to.
  7933. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7934. When not None, the value will be the actual Gerber object for which to create
  7935. the Gerber code
  7936. :param use_thread: if to be run in a separate thread
  7937. :return:
  7938. """
  7939. if filename is None:
  7940. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7941. is not None else self.defaults["global_last_folder"]
  7942. self.app.log.debug("export_gerber()")
  7943. if local_use is None:
  7944. try:
  7945. obj = self.app.collection.get_by_name(str(obj_name))
  7946. except Exception:
  7947. return 'fail'
  7948. else:
  7949. obj = local_use
  7950. # updated units
  7951. gunits = self.defaults["gerber_exp_units"]
  7952. gwhole = self.defaults["gerber_exp_integer"]
  7953. gfract = self.defaults["gerber_exp_decimals"]
  7954. gzeros = self.defaults["gerber_exp_zeros"]
  7955. fc_units = self.defaults['units'].upper()
  7956. if fc_units == 'MM':
  7957. factor = 1 if gunits == 'MM' else 0.03937
  7958. else:
  7959. factor = 25.4 if gunits == 'MM' else 1
  7960. def make_gerber():
  7961. try:
  7962. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7963. header = 'G04*\n'
  7964. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7965. (str(self.app.version), str(self.app.version_date))
  7966. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7967. header += 'G04 Created on : %s*' % time_str + '\n'
  7968. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7969. header += "%MO{units}*%\n".format(units=gunits)
  7970. for apid in obj.apertures:
  7971. if obj.apertures[apid]['type'] == 'C':
  7972. header += "%ADD{apid}{type},{size}*%\n".format(
  7973. apid=str(apid),
  7974. type='C',
  7975. size=(factor * obj.apertures[apid]['size'])
  7976. )
  7977. elif obj.apertures[apid]['type'] == 'R':
  7978. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7979. apid=str(apid),
  7980. type='R',
  7981. width=(factor * obj.apertures[apid]['width']),
  7982. height=(factor * obj.apertures[apid]['height'])
  7983. )
  7984. elif obj.apertures[apid]['type'] == 'O':
  7985. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7986. apid=str(apid),
  7987. type='O',
  7988. width=(factor * obj.apertures[apid]['width']),
  7989. height=(factor * obj.apertures[apid]['height'])
  7990. )
  7991. header += '\n'
  7992. # obsolete units but some software may need it
  7993. if gunits == 'IN':
  7994. header += 'G70*\n'
  7995. else:
  7996. header += 'G71*\n'
  7997. # Absolute Mode
  7998. header += 'G90*\n'
  7999. header += 'G01*\n'
  8000. # positive polarity
  8001. header += '%LPD*%\n'
  8002. footer = 'M02*\n'
  8003. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8004. exported_gerber = header
  8005. exported_gerber += gerber_code
  8006. exported_gerber += footer
  8007. if local_use is None:
  8008. try:
  8009. with open(filename, 'w') as fp:
  8010. fp.write(exported_gerber)
  8011. except PermissionError:
  8012. self.inform.emit('[WARNING] %s' %
  8013. _("Permission denied, saving not possible.\n"
  8014. "Most likely another app is holding the file open and not accessible."))
  8015. return 'fail'
  8016. if self.defaults["global_open_style"] is False:
  8017. self.app.file_opened.emit("Gerber", filename)
  8018. self.app.file_saved.emit("Gerber", filename)
  8019. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  8020. else:
  8021. return exported_gerber
  8022. except Exception as e:
  8023. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8024. return 'fail'
  8025. if use_thread is True:
  8026. with self.app.proc_container.new(_("Exporting Gerber")):
  8027. def job_thread_grb(app_obj):
  8028. ret = make_gerber()
  8029. if ret == 'fail':
  8030. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  8031. return
  8032. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8033. else:
  8034. gret = make_gerber()
  8035. if gret == 'fail':
  8036. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export file.'))
  8037. return 'fail'
  8038. if local_use is not None:
  8039. return gret
  8040. def export_dxf(self, obj_name, filename, local_use=None, use_thread=True):
  8041. """
  8042. Exports a Geometry Object to an DXF file.
  8043. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8044. :param filename: Path to the DXF file to save to.
  8045. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8046. When not None, the value will be the actual Geometry object for which to create
  8047. the Geometry/DXF code
  8048. :param use_thread: if to be run in a separate thread
  8049. :return:
  8050. """
  8051. if filename is None:
  8052. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8053. is not None else self.defaults["global_last_folder"]
  8054. self.app.log.debug("export_dxf()")
  8055. if local_use is None:
  8056. try:
  8057. obj = self.app.collection.get_by_name(str(obj_name))
  8058. except Exception:
  8059. return 'fail'
  8060. else:
  8061. obj = local_use
  8062. def make_dxf():
  8063. try:
  8064. dxf_code = obj.export_dxf()
  8065. if local_use is None:
  8066. try:
  8067. dxf_code.saveas(filename)
  8068. except PermissionError:
  8069. self.inform.emit('[WARNING] %s' %
  8070. _("Permission denied, saving not possible.\n"
  8071. "Most likely another app is holding the file open and not accessible."))
  8072. return 'fail'
  8073. if self.defaults["global_open_style"] is False:
  8074. self.app.file_opened.emit("DXF", filename)
  8075. self.app.file_saved.emit("DXF", filename)
  8076. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  8077. else:
  8078. return dxf_code
  8079. except Exception as e:
  8080. log.debug("App.export_dxf.make_dxf() --> %s" % str(e))
  8081. return 'fail'
  8082. if use_thread is True:
  8083. with self.app.proc_container.new(_("Exporting DXF")):
  8084. def job_thread_exc(app_obj):
  8085. ret_dxf_val = make_dxf()
  8086. if ret_dxf_val == 'fail':
  8087. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8088. return
  8089. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8090. else:
  8091. ret = make_dxf()
  8092. if ret == 'fail':
  8093. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8094. return
  8095. if local_use is not None:
  8096. return ret
  8097. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  8098. """
  8099. Adds a new Geometry Object to the projects and populates
  8100. it with shapes extracted from the SVG file.
  8101. :param plot: If True then the resulting object will be plotted on canvas
  8102. :param filename: Path to the SVG file.
  8103. :param geo_type: Type of FlatCAM object that will be created from SVG
  8104. :param outname: The name given to the resulting FlatCAM object
  8105. :return:
  8106. """
  8107. self.app.log.debug("App.import_svg()")
  8108. obj_type = ""
  8109. if geo_type is None or geo_type == "geometry":
  8110. obj_type = "geometry"
  8111. elif geo_type == "gerber":
  8112. obj_type = "gerber"
  8113. else:
  8114. self.inform.emit('[ERROR_NOTCL] %s' %
  8115. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8116. return
  8117. units = self.defaults['units'].upper()
  8118. def obj_init(geo_obj, app_obj):
  8119. geo_obj.import_svg(filename, obj_type, units=units)
  8120. geo_obj.multigeo = True
  8121. with open(filename) as f:
  8122. file_content = f.read()
  8123. geo_obj.source_file = file_content
  8124. # appGUI feedback
  8125. app_obj.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8126. with self.app.proc_container.new(_("Importing SVG")):
  8127. # Object name
  8128. name = outname or filename.split('/')[-1].split('\\')[-1]
  8129. ret = self.app.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  8130. if ret == 'fail':
  8131. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  8132. return 'fail'
  8133. # Register recent file
  8134. self.app.file_opened.emit("svg", filename)
  8135. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  8136. """
  8137. Adds a new Geometry Object to the projects and populates
  8138. it with shapes extracted from the DXF file.
  8139. :param filename: Path to the DXF file.
  8140. :param geo_type: Type of FlatCAM object that will be created from DXF
  8141. :param outname: Name for the imported Geometry
  8142. :param plot: If True then the resulting object will be plotted on canvas
  8143. :return:
  8144. """
  8145. self.app.log.debug(" ********* Importing DXF as: %s ********* " % geo_type.capitalize())
  8146. obj_type = ""
  8147. if geo_type is None or geo_type == "geometry":
  8148. obj_type = "geometry"
  8149. elif geo_type == "gerber":
  8150. obj_type = geo_type
  8151. else:
  8152. self.inform.emit('[ERROR_NOTCL] %s' %
  8153. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  8154. return
  8155. units = self.defaults['units'].upper()
  8156. def obj_init(geo_obj, app_obj):
  8157. if obj_type == "geometry":
  8158. geo_obj.import_dxf_as_geo(filename, units=units)
  8159. elif obj_type == "gerber":
  8160. geo_obj.import_dxf_as_gerber(filename, units=units)
  8161. else:
  8162. return "fail"
  8163. geo_obj.multigeo = True
  8164. with open(filename) as f:
  8165. file_content = f.read()
  8166. geo_obj.source_file = file_content
  8167. # appGUI feedback
  8168. app_obj.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8169. with self.app.proc_container.new(_("Importing DXF")):
  8170. # Object name
  8171. name = outname or filename.split('/')[-1].split('\\')[-1]
  8172. ret = self.app.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  8173. if ret == 'fail':
  8174. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  8175. return 'fail'
  8176. # Register recent file
  8177. self.app.file_opened.emit("dxf", filename)
  8178. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  8179. """
  8180. Opens a Gerber file, parses it and creates a new object for
  8181. it in the program. Thread-safe.
  8182. :param outname: Name of the resulting object. None causes the
  8183. name to be that of the file. Str.
  8184. :param filename: Gerber file filename
  8185. :type filename: str
  8186. :param plot: boolean, to plot or not the resulting object
  8187. :param from_tcl: True if run from Tcl Shell
  8188. :return: None
  8189. """
  8190. # How the object should be initialized
  8191. def obj_init(gerber_obj, app_obj):
  8192. assert isinstance(gerber_obj, GerberObject), \
  8193. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  8194. # Opening the file happens here
  8195. try:
  8196. gerber_obj.parse_file(filename)
  8197. except IOError:
  8198. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8199. return "fail"
  8200. except ParseError as err:
  8201. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8202. app_obj.log.error(str(err))
  8203. return "fail"
  8204. except Exception as e:
  8205. log.debug("App.open_gerber() --> %s" % str(e))
  8206. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8207. msg += traceback.format_exc()
  8208. app_obj.inform.emit(msg)
  8209. return "fail"
  8210. if gerber_obj.is_empty():
  8211. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8212. _("Object is not Gerber file or empty. Aborting object creation."))
  8213. return "fail"
  8214. self.app.log.debug("open_gerber()")
  8215. with self.app.proc_container.new(_("Opening Gerber")):
  8216. # Object name
  8217. name = outname or filename.split('/')[-1].split('\\')[-1]
  8218. # # ## Object creation # ##
  8219. ret_val = self.app.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  8220. if ret_val == 'fail':
  8221. if from_tcl:
  8222. filename = self.defaults['global_tcl_path'] + '/' + name
  8223. ret_val = self.app.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  8224. if ret_val == 'fail':
  8225. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  8226. return 'fail'
  8227. # Register recent file
  8228. self.app.file_opened.emit("gerber", filename)
  8229. # appGUI feedback
  8230. self.app.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8231. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  8232. """
  8233. Opens an Excellon file, parses it and creates a new object for
  8234. it in the program. Thread-safe.
  8235. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8236. :param filename: Excellon file filename
  8237. :type filename: str
  8238. :param plot: boolean, to plot or not the resulting object
  8239. :param from_tcl: True if run from Tcl Shell
  8240. :return: None
  8241. """
  8242. self.app.log.debug("open_excellon()")
  8243. # How the object should be initialized
  8244. def obj_init(excellon_obj, app_obj):
  8245. try:
  8246. ret = excellon_obj.parse_file(filename=filename)
  8247. if ret == "fail":
  8248. app_obj.log.debug("Excellon parsing failed.")
  8249. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not Excellon file."))
  8250. return "fail"
  8251. except IOError:
  8252. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Cannot open file"), filename))
  8253. app_obj.log.debug("Could not open Excellon object.")
  8254. return "fail"
  8255. except Exception:
  8256. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8257. msg += traceback.format_exc()
  8258. app_obj.inform.emit(msg)
  8259. return "fail"
  8260. ret = excellon_obj.create_geometry()
  8261. if ret == 'fail':
  8262. app_obj.log.debug("Could not create geometry for Excellon object.")
  8263. return "fail"
  8264. for tool in excellon_obj.tools:
  8265. if excellon_obj.tools[tool]['solid_geometry']:
  8266. return
  8267. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  8268. return "fail"
  8269. with self.app.proc_container.new(_("Opening Excellon.")):
  8270. # Object name
  8271. name = outname or filename.split('/')[-1].split('\\')[-1]
  8272. ret_val = self.app.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8273. if ret_val == 'fail':
  8274. if from_tcl:
  8275. filename = self.defaults['global_tcl_path'] + '/' + name
  8276. ret_val = self.app.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8277. if ret_val == 'fail':
  8278. self.inform.emit('[ERROR_NOTCL] %s' %
  8279. _('Open Excellon file failed. Probable not an Excellon file.'))
  8280. return
  8281. # Register recent file
  8282. self.app.file_opened.emit("excellon", filename)
  8283. # appGUI feedback
  8284. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8285. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  8286. """
  8287. Opens a G-gcode file, parses it and creates a new object for
  8288. it in the program. Thread-safe.
  8289. :param filename: G-code file filename
  8290. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8291. :param force_parsing:
  8292. :param plot: If True plot the object on canvas
  8293. :param from_tcl: True if run from Tcl Shell
  8294. :return: None
  8295. """
  8296. self.app.log.debug("open_gcode()")
  8297. # How the object should be initialized
  8298. def obj_init(job_obj, app_obj_):
  8299. """
  8300. :param job_obj: the resulting object
  8301. :type app_obj_: App
  8302. """
  8303. assert isinstance(app_obj_, App), \
  8304. "Initializer expected App, got %s" % type(app_obj_)
  8305. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  8306. try:
  8307. f = open(filename)
  8308. gcode = f.read()
  8309. f.close()
  8310. except IOError:
  8311. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  8312. return "fail"
  8313. job_obj.gcode = gcode
  8314. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  8315. if gcode_ret == "fail":
  8316. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  8317. return "fail"
  8318. job_obj.create_geometry()
  8319. with self.app.proc_container.new(_("Opening G-Code.")):
  8320. # Object name
  8321. name = outname or filename.split('/')[-1].split('\\')[-1]
  8322. # New object creation and file processing
  8323. ret_val = self.app.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8324. if ret_val == 'fail':
  8325. if from_tcl:
  8326. filename = self.defaults['global_tcl_path'] + '/' + name
  8327. ret_val = self.app.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8328. if ret_val == 'fail':
  8329. self.inform.emit('[ERROR_NOTCL] %s' %
  8330. _("Failed to create CNCJob Object. Probable not a GCode file. "
  8331. "Try to load it from File menu.\n "
  8332. "Attempting to create a FlatCAM CNCJob Object from "
  8333. "G-Code file failed during processing"))
  8334. return "fail"
  8335. # Register recent file
  8336. self.app.file_opened.emit("cncjob", filename)
  8337. # appGUI feedback
  8338. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8339. def open_hpgl2(self, filename, outname=None):
  8340. """
  8341. Opens a HPGL2 file, parses it and creates a new object for
  8342. it in the program. Thread-safe.
  8343. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8344. :param filename: HPGL2 file filename
  8345. :return: None
  8346. """
  8347. filename = filename
  8348. # How the object should be initialized
  8349. def obj_init(geo_obj, app_obj):
  8350. assert isinstance(geo_obj, GeometryObject), \
  8351. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  8352. # Opening the file happens here
  8353. obj = HPGL2(self)
  8354. try:
  8355. HPGL2.parse_file(obj, filename)
  8356. except IOError:
  8357. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8358. return "fail"
  8359. except ParseError as err:
  8360. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8361. app_obj.log.error(str(err))
  8362. return "fail"
  8363. except Exception as e:
  8364. app_obj.log.debug("App.open_hpgl2() --> %s" % str(e))
  8365. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8366. msg += traceback.format_exc()
  8367. app_obj.inform.emit(msg)
  8368. return "fail"
  8369. geo_obj.multigeo = True
  8370. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  8371. geo_obj.tools = deepcopy(obj.tools)
  8372. geo_obj.source_file = deepcopy(obj.source_file)
  8373. del obj
  8374. if not geo_obj.solid_geometry:
  8375. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  8376. _("Object is not HPGL2 file or empty. Aborting object creation."))
  8377. return "fail"
  8378. self.app.log.debug("open_hpgl2()")
  8379. with self.app.proc_container.new(_("Opening HPGL2")):
  8380. # Object name
  8381. name = outname or filename.split('/')[-1].split('\\')[-1]
  8382. # # ## Object creation # ##
  8383. ret = self.app.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  8384. if ret == 'fail':
  8385. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  8386. return 'fail'
  8387. # Register recent file
  8388. self.app.file_opened.emit("geometry", filename)
  8389. # appGUI feedback
  8390. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8391. def open_script(self, filename, outname=None, silent=False):
  8392. """
  8393. Opens a Script file, parses it and creates a new object for
  8394. it in the program. Thread-safe.
  8395. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8396. :param filename: Script file filename
  8397. :param silent: If True there will be no messages printed to StatusBar
  8398. :return: None
  8399. """
  8400. def obj_init(script_obj, app_obj):
  8401. assert isinstance(script_obj, ScriptObject), \
  8402. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  8403. if silent is False:
  8404. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  8405. try:
  8406. script_obj.parse_file(filename)
  8407. except IOError:
  8408. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  8409. return "fail"
  8410. except ParseError as err:
  8411. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  8412. app_obj.log.error(str(err))
  8413. return "fail"
  8414. except Exception as e:
  8415. app_obj.log.debug("App.open_script() -> %s" % str(e))
  8416. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  8417. msg += traceback.format_exc()
  8418. app_obj.inform.emit(msg)
  8419. return "fail"
  8420. self.app.log.debug("open_script()")
  8421. with self.app.proc_container.new(_("Opening TCL Script...")):
  8422. # Object name
  8423. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  8424. # Object creation
  8425. ret_val = self.app.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  8426. if ret_val == 'fail':
  8427. filename = self.defaults['global_tcl_path'] + '/' + script_name
  8428. ret_val = self.app.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  8429. if ret_val == 'fail':
  8430. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  8431. return 'fail'
  8432. # Register recent file
  8433. self.app.file_opened.emit("script", filename)
  8434. # appGUI feedback
  8435. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  8436. def open_config_file(self, filename, run_from_arg=None):
  8437. """
  8438. Loads a config file from the specified file.
  8439. :param filename: Name of the file from which to load.
  8440. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  8441. :return: None
  8442. """
  8443. self.app.log.debug("Opening config file: " + filename)
  8444. if run_from_arg:
  8445. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8446. "Canvas initialization finished in"),
  8447. '%.2f' % self.app.used_time,
  8448. _("Opening FlatCAM Config file.")),
  8449. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8450. color=QtGui.QColor("gray"))
  8451. # # add the tab if it was closed
  8452. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  8453. # # first clear previous text in text editor (if any)
  8454. # self.ui.text_editor_tab.code_editor.clear()
  8455. #
  8456. # # Switch plot_area to CNCJob tab
  8457. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  8458. # close the Code editor if already open
  8459. if self.app.toggle_codeeditor:
  8460. self.app.on_toggle_code_editor()
  8461. self.app.on_toggle_code_editor()
  8462. try:
  8463. if filename:
  8464. f = QtCore.QFile(filename)
  8465. if f.open(QtCore.QIODevice.ReadOnly):
  8466. stream = QtCore.QTextStream(f)
  8467. code_edited = stream.readAll()
  8468. self.app.text_editor_tab.load_text(code_edited, clear_text=True, move_to_start=True)
  8469. f.close()
  8470. except IOError:
  8471. self.app.log.error("Failed to open config file: %s" % filename)
  8472. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open config file"), filename))
  8473. return
  8474. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  8475. """
  8476. Loads a project from the specified file.
  8477. 1) Loads and parses file
  8478. 2) Registers the file as recently opened.
  8479. 3) Calls on_file_new()
  8480. 4) Updates options
  8481. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  8482. 6) Calls plot_all() if plot=True
  8483. :param filename: Name of the file from which to load.
  8484. :param run_from_arg: True if run for arguments
  8485. :param plot: If True plot all objects in the project
  8486. :param cli: Run from command line
  8487. :param from_tcl: True if run from Tcl Sehll
  8488. :return: None
  8489. """
  8490. self.app.log.debug("Opening project: " + filename)
  8491. # block autosaving while a project is loaded
  8492. self.app.block_autosave = True
  8493. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8494. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8495. if cli is None:
  8496. self.app.ui.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8497. if run_from_arg:
  8498. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8499. "Canvas initialization finished in"),
  8500. '%.2f' % self.app.used_time,
  8501. _("Opening FlatCAM Project file.")),
  8502. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8503. color=QtGui.QColor("gray"))
  8504. # Open and parse an uncompressed Project file
  8505. try:
  8506. f = open(filename, 'r')
  8507. except IOError:
  8508. if from_tcl:
  8509. name = filename.split('/')[-1].split('\\')[-1]
  8510. filename = self.defaults['global_tcl_path'] + '/' + name
  8511. try:
  8512. f = open(filename, 'r')
  8513. except IOError:
  8514. self.app.log.error("Failed to open project file: %s" % filename)
  8515. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8516. return
  8517. else:
  8518. self.app.log.error("Failed to open project file: %s" % filename)
  8519. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8520. return
  8521. try:
  8522. d = json.load(f, object_hook=dict2obj)
  8523. except Exception as e:
  8524. self.app.log.error(
  8525. "Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8526. (filename, str(e)))
  8527. f.close()
  8528. # Open and parse a compressed Project file
  8529. try:
  8530. with lzma.open(filename) as f:
  8531. file_content = f.read().decode('utf-8')
  8532. d = json.loads(file_content, object_hook=dict2obj)
  8533. except Exception as e:
  8534. self.app.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8535. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8536. return
  8537. # Clear the current project
  8538. # # NOT THREAD SAFE # ##
  8539. if run_from_arg is True:
  8540. pass
  8541. elif cli is True:
  8542. self.app.delete_selection_shape()
  8543. else:
  8544. self.on_file_new()
  8545. # Project options
  8546. self.app.options.update(d['options'])
  8547. self.app.project_filename = filename
  8548. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8549. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8550. if cli is None:
  8551. self.app.set_screen_units(self.app.options["units"])
  8552. # Re create objects
  8553. self.app.log.debug(" **************** Started PROEJCT loading... **************** ")
  8554. for obj in d['objs']:
  8555. def obj_init(obj_inst, app_inst):
  8556. try:
  8557. obj_inst.from_dict(obj)
  8558. except Exception as erro:
  8559. app_inst.log('MenuFileHandlers.open_project() --> ' + str(erro))
  8560. return 'fail'
  8561. self.app.log.debug(
  8562. "Recreating from opened project an %s object: %s" % (obj['kind'].capitalize(), obj['options']['name']))
  8563. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8564. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8565. if cli is None:
  8566. self.app.ui.set_ui_title(name="{} {}: {}".format(
  8567. _("Loading Project ... restoring"), obj['kind'].upper(), obj['options']['name']))
  8568. self.app.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  8569. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8570. self.app.should_we_save = False
  8571. self.app.file_opened.emit("project", filename)
  8572. # restore autosaving after a project was loaded
  8573. self.app.block_autosave = False
  8574. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8575. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8576. if cli is None:
  8577. self.app.ui.set_ui_title(name=self.app.project_filename)
  8578. self.app.log.debug(" **************** Finished PROJECT loading... **************** ")
  8579. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8580. """
  8581. Saves the current project to the specified file.
  8582. :param filename: Name of the file in which to save.
  8583. :type filename: str
  8584. :param quit_action: if the project saving will be followed by an app quit; boolean
  8585. :param silent: if True will not display status messages
  8586. :param from_tcl True is run from Tcl Shell
  8587. :return: None
  8588. """
  8589. self.app.log.debug("save_project()")
  8590. self.app.save_in_progress = True
  8591. if from_tcl:
  8592. log.debug("MenuFileHandlers.save_project() -> Project saved from TCL command.")
  8593. with self.app.proc_container.new(_("Saving FlatCAM Project")):
  8594. # Capture the latest changes
  8595. # Current object
  8596. try:
  8597. current_object = self.app.collection.get_active()
  8598. if current_object:
  8599. current_object.read_form()
  8600. except Exception as e:
  8601. self.app.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8602. # Serialize the whole project
  8603. d = {
  8604. "objs": [obj.to_dict() for obj in self.app.collection.get_list()],
  8605. "options": self.app.options,
  8606. "version": self.app.version
  8607. }
  8608. if self.defaults["global_save_compressed"] is True:
  8609. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8610. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8611. # # Write
  8612. f.write(g)
  8613. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8614. else:
  8615. # Open file
  8616. try:
  8617. f = open(filename, 'w')
  8618. except IOError:
  8619. self.app.log.error("Failed to open file for saving: %s", filename)
  8620. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8621. return
  8622. # Write
  8623. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8624. f.close()
  8625. # verification of the saved project
  8626. # Open and parse
  8627. try:
  8628. saved_f = open(filename, 'r')
  8629. except IOError:
  8630. if silent is False:
  8631. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8632. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8633. return
  8634. try:
  8635. saved_d = json.load(saved_f, object_hook=dict2obj)
  8636. except Exception:
  8637. if silent is False:
  8638. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8639. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8640. f.close()
  8641. return
  8642. saved_f.close()
  8643. if silent is False:
  8644. if 'version' in saved_d:
  8645. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8646. else:
  8647. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8648. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8649. tb_settings = QSettings("Open Source", "FlatCAM")
  8650. lock_state = self.app.ui.lock_action.isChecked()
  8651. tb_settings.setValue('toolbar_lock', lock_state)
  8652. # This will write the setting to the platform specific storage.
  8653. del tb_settings
  8654. # if quit:
  8655. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8656. # t.start()
  8657. self.app.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8658. def save_source_file(self, obj_name, filename):
  8659. """
  8660. Exports a FlatCAM Object to an Gerber/Excellon file.
  8661. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8662. :param filename: Path to the Gerber file to save to.
  8663. :return:
  8664. """
  8665. if filename is None:
  8666. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8667. is not None else self.defaults["global_last_folder"]
  8668. self.app.log.debug("save source file()")
  8669. obj = self.app.collection.get_by_name(obj_name)
  8670. file_string = StringIO(obj.source_file)
  8671. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8672. if file_string.getvalue() == '':
  8673. self.inform.emit('[ERROR_NOTCL] %s' %
  8674. _("Save cancelled because source file is empty. Try to export the file."))
  8675. return 'fail'
  8676. try:
  8677. with open(filename, 'w') as file:
  8678. file.writelines('G04*\n')
  8679. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8680. (obj.kind.upper(), str(self.app.version), str(self.app.version_date)))
  8681. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8682. file.writelines('G04 Created on : %s*\n' % time_string)
  8683. for line in file_string:
  8684. file.writelines(line)
  8685. except PermissionError:
  8686. self.inform.emit('[WARNING] %s' %
  8687. _("Permission denied, saving not possible.\n"
  8688. "Most likely another app is holding the file open and not accessible."))
  8689. return 'fail'
  8690. def on_file_savedefaults(self):
  8691. """
  8692. Callback for menu item File->Save Defaults. Saves application default options
  8693. ``self.defaults`` to current_defaults.FlatConfig.
  8694. :return: None
  8695. """
  8696. self.app.preferencesUiManager.save_defaults()
  8697. # end of file