FlatCAMApp.py 494 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994
  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. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import threading
  16. import shutil
  17. from stat import S_IREAD, S_IRGRP, S_IROTH
  18. import subprocess
  19. import ctypes
  20. import tkinter as tk
  21. from PyQt5 import QtPrintSupport
  22. from contextlib import contextmanager
  23. import gc
  24. from xml.dom.minidom import parseString as parse_xml_string
  25. from multiprocessing.connection import Listener, Client
  26. from multiprocessing import Pool
  27. import socket
  28. from array import array
  29. # #######################################
  30. # # Imports part of FlatCAM ##
  31. # #######################################
  32. from ObjectCollection import *
  33. from FlatCAMObj import *
  34. from flatcamGUI.PlotCanvas import *
  35. from flatcamGUI.FlatCAMGUI import *
  36. from FlatCAMCommon import LoudDict
  37. from FlatCAMPostProc import load_postprocessors
  38. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  39. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  40. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  41. from FlatCAMProcess import *
  42. from FlatCAMWorkerStack import WorkerStack
  43. from flatcamGUI.VisPyVisuals import Color
  44. from vispy.gloo.util import _screenshot
  45. from vispy.io import write_png
  46. from flatcamTools import *
  47. import tclCommands
  48. import gettext
  49. import FlatCAMTranslation as fcTranslate
  50. import builtins
  51. if sys.platform == 'win32':
  52. import winreg
  53. fcTranslate.apply_language('strings')
  54. if '_' not in builtins.__dict__:
  55. _ = gettext.gettext
  56. # ########################################
  57. # # App ###
  58. # ########################################
  59. class App(QtCore.QObject):
  60. """
  61. The main application class. The constructor starts the GUI.
  62. """
  63. # Get Cmd Line Options
  64. cmd_line_shellfile = ''
  65. cmd_line_shellvars = ''
  66. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\nFlatCam.py --shellvars=<cmd_line_shellvars"
  67. try:
  68. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  69. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  70. "shellvars=",
  71. "multiprocessing-fork="])
  72. except getopt.GetoptError:
  73. print(cmd_line_help)
  74. sys.exit(2)
  75. for opt, arg in cmd_line_options:
  76. if opt == '-h':
  77. print(cmd_line_help)
  78. sys.exit()
  79. elif opt == '--shellfile':
  80. cmd_line_shellfile = arg
  81. elif opt == '--shellvars':
  82. cmd_line_shellvars = arg
  83. # ## Logging ###
  84. log = logging.getLogger('base')
  85. log.setLevel(logging.DEBUG)
  86. # log.setLevel(logging.WARNING)
  87. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  88. handler = logging.StreamHandler()
  89. handler.setFormatter(formatter)
  90. log.addHandler(handler)
  91. # ##########################################################################
  92. # ################## Version and VERSION DATE ##############################
  93. # ##########################################################################
  94. version = 8.97
  95. version_date = "2019/09/20"
  96. beta = True
  97. # current date now
  98. date = str(datetime.today()).rpartition('.')[0]
  99. date = ''.join(c for c in date if c not in ':-')
  100. date = date.replace(' ', '_')
  101. # URL for update checks and statistics
  102. version_url = "http://flatcam.org/version"
  103. # App URL
  104. app_url = "http://flatcam.org"
  105. # Manual URL
  106. manual_url = "http://flatcam.org/manual/index.html"
  107. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  108. gerber_spec_url ="https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  109. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  110. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  111. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  112. # this variable will hold the project status
  113. # if True it will mean that the project was modified and not saved
  114. should_we_save = False
  115. # flag is True if saving action has been triggered
  116. save_in_progress = False
  117. # ###########################################################################
  118. # ############################# Signals ################################
  119. # ###########################################################################
  120. # Inform the user
  121. # Handled by:
  122. # * App.info() --> Print on the status bar
  123. inform = QtCore.pyqtSignal(str)
  124. app_quit = QtCore.pyqtSignal()
  125. # General purpose background task
  126. worker_task = QtCore.pyqtSignal(dict)
  127. # File opened
  128. # Handled by:
  129. # * register_folder()
  130. # * register_recent()
  131. # Note: Setting the parameters to unicode does not seem
  132. # to have an effect. Then are received as Qstring
  133. # anyway.
  134. # File type and filename
  135. file_opened = QtCore.pyqtSignal(str, str)
  136. # File type and filename
  137. file_saved = QtCore.pyqtSignal(str, str)
  138. # Percentage of progress
  139. progress = QtCore.pyqtSignal(int)
  140. plots_updated = QtCore.pyqtSignal()
  141. # Emitted by new_object() and passes the new object as argument, plot flag.
  142. # on_object_created() adds the object to the collection, plots on appropriate flag
  143. # and emits new_object_available.
  144. object_created = QtCore.pyqtSignal(object, bool, bool)
  145. # Emitted when a object has been changed (like scaled, mirrored)
  146. object_changed = QtCore.pyqtSignal(object)
  147. # Emitted after object has been plotted.
  148. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  149. object_plotted = QtCore.pyqtSignal(object)
  150. # Emitted when a new object has been added or deleted from/to the collection
  151. object_status_changed = QtCore.pyqtSignal(object, str)
  152. message = QtCore.pyqtSignal(str, str, str)
  153. # Emmited when shell command is finished(one command only)
  154. shell_command_finished = QtCore.pyqtSignal(object)
  155. # Emitted when multiprocess pool has been recreated
  156. pool_recreated = QtCore.pyqtSignal(object)
  157. # Emitted when an unhandled exception happens
  158. # in the worker task.
  159. thread_exception = QtCore.pyqtSignal(object)
  160. # used to signal that there are arguments for the app
  161. args_at_startup = QtCore.pyqtSignal(list)
  162. # a reusable signal to replot a list of objects
  163. # should be disconnected after use so it can be reused
  164. replot_signal = pyqtSignal(list)
  165. def __init__(self, user_defaults=True, post_gui=None):
  166. """
  167. Starts the application.
  168. :return: app
  169. :rtype: App
  170. """
  171. App.log.info("FlatCAM Starting...")
  172. self.main_thread = QtWidgets.QApplication.instance().thread()
  173. # ############################################################################
  174. # # ################# OS-specific ############################################
  175. # ############################################################################
  176. portable = False
  177. # Folder for user settings.
  178. if sys.platform == 'win32':
  179. # #########################################################################
  180. # Setup the listening thread for another instance launching with args #####
  181. # #########################################################################
  182. # make sure the thread is stored by using a self. otherwise it's garbage collected
  183. self.th = QtCore.QThread()
  184. self.th.start(priority=QtCore.QThread.LowestPriority)
  185. self.new_launch = ArgsThread()
  186. self.new_launch.open_signal[list].connect(self.on_startup_args)
  187. self.new_launch.moveToThread(self.th)
  188. self.new_launch.start.emit()
  189. from win32com.shell import shell, shellcon
  190. if platform.architecture()[0] == '32bit':
  191. App.log.debug("Win32!")
  192. else:
  193. App.log.debug("Win64!")
  194. # #########################################################################
  195. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  196. # #########################################################################
  197. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  198. try:
  199. with open(config_file, 'r') as f:
  200. try:
  201. for line in f:
  202. param = str(line).rpartition('=')
  203. if param[0] == 'portable':
  204. try:
  205. portable = eval(param[2])
  206. except NameError:
  207. portable = False
  208. except Exception as e:
  209. log.debug('App.__init__() -->%s' % str(e))
  210. return
  211. except FileNotFoundError:
  212. pass
  213. if portable is False:
  214. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  215. else:
  216. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  217. self.os = 'windows'
  218. else: # Linux/Unix/MacOS
  219. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  220. self.os = 'unix'
  221. # ##########################################################################
  222. # ################## Setup folders and files ###############################
  223. # ##########################################################################
  224. if not os.path.exists(self.data_path):
  225. os.makedirs(self.data_path)
  226. App.log.debug('Created data folder: ' + self.data_path)
  227. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  228. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  229. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  230. if not os.path.exists(self.postprocessorpaths):
  231. os.makedirs(self.postprocessorpaths)
  232. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  233. # create current_defaults.FlatConfig file if there is none
  234. try:
  235. f = open(self.data_path + '/current_defaults.FlatConfig')
  236. f.close()
  237. except IOError:
  238. App.log.debug('Creating empty current_defaults.FlatConfig')
  239. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  240. json.dump({}, f)
  241. f.close()
  242. # create factory_defaults.FlatConfig file if there is none
  243. try:
  244. f = open(self.data_path + '/factory_defaults.FlatConfig')
  245. f.close()
  246. except IOError:
  247. App.log.debug('Creating empty factory_defaults.FlatConfig')
  248. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  249. json.dump({}, f)
  250. f.close()
  251. try:
  252. f = open(self.data_path + '/recent.json')
  253. f.close()
  254. except IOError:
  255. App.log.debug('Creating empty recent.json')
  256. f = open(self.data_path + '/recent.json', 'w')
  257. json.dump([], f)
  258. f.close()
  259. try:
  260. fp = open(self.data_path + '/recent_projects.json')
  261. fp.close()
  262. except IOError:
  263. App.log.debug('Creating empty recent_projects.json')
  264. fp = open(self.data_path + '/recent_projects.json', 'w')
  265. json.dump([], fp)
  266. fp.close()
  267. # Application directory. CHDIR to it. Otherwise, trying to load
  268. # GUI icons will fail as their path is relative.
  269. # This will fail under cx_freeze ...
  270. self.app_home = os.path.dirname(os.path.realpath(__file__))
  271. App.log.debug("Application path is " + self.app_home)
  272. App.log.debug("Started in " + os.getcwd())
  273. # cx_freeze workaround
  274. if os.path.isfile(self.app_home):
  275. self.app_home = os.path.dirname(self.app_home)
  276. os.chdir(self.app_home)
  277. # #############################################################################
  278. # ##################### CREATE MULTIPROCESSING POOL ###########################
  279. # #############################################################################
  280. self.pool = Pool()
  281. # ##########################################################################
  282. # ################## Setting the Splash Screen #############################
  283. # ##########################################################################
  284. settings = QSettings("Open Source", "FlatCAM")
  285. if settings.contains("splash_screen"):
  286. show_splash = settings.value("splash_screen")
  287. else:
  288. settings.setValue('splash_screen', 1)
  289. # This will write the setting to the platform specific storage.
  290. del settings
  291. show_splash = 1
  292. if show_splash:
  293. splash_pix = QtGui.QPixmap('share/splash.png')
  294. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  295. # self.splash.setMask(splash_pix.mask())
  296. # move splashscreen to the current monitor
  297. desktop = QtWidgets.QApplication.desktop()
  298. screen = desktop.screenNumber(QtGui.QCursor.pos())
  299. current_screen_center = desktop.availableGeometry(screen).center()
  300. self.splash.move(current_screen_center - self.splash.rect().center())
  301. self.splash.show()
  302. self.splash.showMessage(_("FlatCAM is initializing ..."),
  303. alignment=Qt.AlignBottom | Qt.AlignLeft,
  304. color=QtGui.QColor("gray"))
  305. # #############################################################################
  306. # ##################### Initialize GUI ########################################
  307. # #############################################################################
  308. # FlatCAM colors used in plotting
  309. self.FC_light_green = '#BBF268BF'
  310. self.FC_dark_green = '#006E20BF'
  311. self.FC_light_blue = '#a5a5ffbf'
  312. self.FC_dark_blue = '#0000ffbf'
  313. QtCore.QObject.__init__(self)
  314. self.ui = FlatCAMGUI(self.version, self.beta, self)
  315. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  316. self.ui.final_save.connect(self.final_save)
  317. # #############################################################################
  318. # ############################## Data #########################################
  319. # #############################################################################
  320. self.recent = []
  321. self.recent_projects = []
  322. self.clipboard = QtWidgets.QApplication.clipboard()
  323. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  324. self.project_filename = None
  325. self.toggle_units_ignore = False
  326. # self.defaults_form = PreferencesUI()
  327. # when adding entries here read the comments in the method found bellow named:
  328. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  329. self.defaults_form_fields = {
  330. # General App
  331. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  332. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  333. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  334. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  335. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  336. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  337. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  338. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  339. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  340. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  341. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  342. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  343. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  344. # General GUI Preferences
  345. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  346. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  347. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  348. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  349. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  350. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  351. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  352. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  353. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  354. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  355. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  356. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  357. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  358. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  359. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  360. # General GUI Settings
  361. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  362. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  363. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  364. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  365. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  366. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  367. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  368. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  369. # Gerber General
  370. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  371. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  372. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  373. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  374. # Gerber Options
  375. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  376. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  377. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  378. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  379. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  380. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  381. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  382. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  383. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  384. # Gerber Advanced Options
  385. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  386. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  387. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  388. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  389. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  390. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  391. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  392. # Gerber Export
  393. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  394. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  395. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  396. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  397. # Gerber Editor
  398. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  399. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  400. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  401. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  402. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  403. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  404. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  405. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  406. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  407. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  408. "gerber_editor_circ_angle":
  409. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  410. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  411. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  412. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  413. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  414. # Excellon General
  415. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  416. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  417. "excellon_format_upper_in":
  418. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  419. "excellon_format_lower_in":
  420. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  421. "excellon_format_upper_mm":
  422. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  423. "excellon_format_lower_mm":
  424. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  425. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  426. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  427. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  428. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  429. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  430. # Excellon Options
  431. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  432. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  433. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  434. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  435. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  436. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  437. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  438. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  439. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  440. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  441. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  442. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  443. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  444. # Excellon Advanced Options
  445. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  446. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  447. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  448. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  449. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  450. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  451. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  452. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  453. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  454. # Excellon Export
  455. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  456. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  457. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  458. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  459. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  460. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  461. # Excellon Editor
  462. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  463. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  464. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  465. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  466. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  467. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  468. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  469. "excellon_editor_circ_angle":
  470. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  471. # Excellon Slots
  472. "excellon_editor_slot_direction":
  473. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  474. "excellon_editor_slot_angle":
  475. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  476. "excellon_editor_slot_length":
  477. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  478. # Excellon Slots
  479. "excellon_editor_slot_array_size":
  480. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  481. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  482. "excellon_editor_slot_lin_pitch":
  483. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  484. "excellon_editor_slot_lin_angle":
  485. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  486. "excellon_editor_slot_circ_dir":
  487. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  488. "excellon_editor_slot_circ_angle":
  489. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  490. # Geometry General
  491. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  492. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  493. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  494. # Geometry Options
  495. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  496. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  497. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  498. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  499. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  500. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  501. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  502. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  503. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  504. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  505. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  506. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  507. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  508. # Geometry Advanced Options
  509. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  510. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  511. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  512. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  513. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  514. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  515. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  516. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  517. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  518. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  519. # Geometry Editor
  520. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  521. # CNCJob General
  522. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  523. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  524. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  525. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  526. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  527. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  528. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  529. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  530. # CNC Job Options
  531. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  532. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  533. # CNC Job Advanced Options
  534. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  535. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  536. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  537. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  538. # NCC Tool
  539. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  540. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  541. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  542. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  543. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  544. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  545. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  546. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  547. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  548. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  549. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  550. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  551. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  552. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  553. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  554. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  555. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  556. # CutOut Tool
  557. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  558. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  559. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  560. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  561. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  562. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  563. # Paint Area Tool
  564. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  565. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  566. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  567. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  568. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  569. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  570. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  571. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  572. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  573. # 2-sided Tool
  574. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  575. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  576. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  577. # Film Tool
  578. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  579. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  580. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  581. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  582. # Panelize Tool
  583. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  584. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  585. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  586. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  587. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  588. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  589. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  590. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  591. # Calculators Tool
  592. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  593. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  594. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  595. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  596. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  597. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  598. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  599. # Transformations Tool
  600. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  601. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  602. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  603. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  604. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  605. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  606. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  607. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  608. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  609. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  610. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  611. # SolderPaste Dispensing Tool
  612. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  613. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  614. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  615. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  616. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  617. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  618. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  619. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  620. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  621. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  622. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  623. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  624. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  625. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  626. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  627. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  628. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  629. # file associations
  630. "fa_excellon": self.ui.fa_defaults_form.fa_excellon_group.exc_list_text,
  631. "fa_gcode": self.ui.fa_defaults_form.fa_gcode_group.gco_list_text,
  632. # "fa_geometry": self.ui.fa_defaults_form.fa_geometry_group.close_paths_cb,
  633. "fa_gerber": self.ui.fa_defaults_form.fa_gerber_group.grb_list_text,
  634. }
  635. # ############################
  636. # ### LOAD POSTPROCESSORS ####
  637. # ############################
  638. self.postprocessors = load_postprocessors(self)
  639. for name in list(self.postprocessors.keys()):
  640. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  641. if name.partition('_')[0] == 'Paste':
  642. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  643. continue
  644. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  645. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  646. if name == 'hpgl':
  647. continue
  648. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  649. # ############################
  650. # ### LOAD LANGUAGES ####
  651. # ############################
  652. self.languages = fcTranslate.load_languages()
  653. for name in sorted(self.languages.values()):
  654. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  655. self.defaults = LoudDict()
  656. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  657. self.defaults.update({
  658. # Global APP Preferences
  659. "first_run": True,
  660. "units": "IN",
  661. "global_serial": 0,
  662. "global_stats": {},
  663. "global_tabs_detachable": True,
  664. "global_app_level": 'b',
  665. "global_portable": False,
  666. "global_language": 'English',
  667. "global_version_check": True,
  668. "global_send_stats": True,
  669. "global_pan_button": '2',
  670. "global_mselect_key": 'Control',
  671. "global_project_at_startup": False,
  672. "global_project_autohide": True,
  673. "global_toggle_tooltips": True,
  674. "global_worker_number": 2,
  675. "global_tolerance": 0.01,
  676. "global_open_style": True,
  677. "global_delete_confirmation": True,
  678. "global_compression_level": 3,
  679. "global_save_compressed": True,
  680. # Global GUI Preferences
  681. "global_gridx": 0.0393701,
  682. "global_gridy": 0.0393701,
  683. "global_snap_max": 0.001968504,
  684. "global_workspace": False,
  685. "global_workspaceT": "A4P",
  686. "global_grid_context_menu": {
  687. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  688. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  689. },
  690. "global_plot_fill": '#BBF268BF',
  691. "global_plot_line": '#006E20BF',
  692. "global_sel_fill": '#a5a5ffbf',
  693. "global_sel_line": '#0000ffbf',
  694. "global_alt_sel_fill": '#BBF268BF',
  695. "global_alt_sel_line": '#006E20BF',
  696. "global_draw_color": '#FF0000',
  697. "global_sel_draw_color": '#0000FF',
  698. "global_proj_item_color": '#000000',
  699. "global_proj_item_dis_color": '#b7b7cb',
  700. "global_toolbar_view": 511,
  701. "global_background_timeout": 300000, # Default value is 5 minutes
  702. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  703. # (python trace only for unknown errors),
  704. # 1 = show trace(show trace always),
  705. # 2 = (For the future).
  706. # Persistence
  707. "global_last_folder": None,
  708. "global_last_save_folder": None,
  709. # Default window geometry
  710. "global_def_win_x": 100,
  711. "global_def_win_y": 100,
  712. "global_def_win_w": 1024,
  713. "global_def_win_h": 650,
  714. "global_def_notebook_width": 1,
  715. # Constants...
  716. "global_defaults_save_period_ms": 20000, # Time between default saves.
  717. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  718. "global_shell_at_startup": False, # Show the shell at startup.
  719. "global_recent_limit": 10, # Max. items in recent list.
  720. "fit_key": 'V',
  721. "zoom_out_key": '-',
  722. "zoom_in_key": '=',
  723. "grid_toggle_key": 'G',
  724. "global_zoom_ratio": 1.5,
  725. "global_point_clipboard_format": "(%.4f, %.4f)",
  726. "global_zdownrate": None,
  727. # autocomplete keywords
  728. "global_autocomplete_keywords":
  729. ['all', 'angle_x', 'angle_y', 'axis', 'axisoffset', 'box', 'center_x', 'center_y',
  730. 'columns', 'combine', 'connect', 'contour', 'depthperpass', 'dia', 'diatol', 'dist',
  731. 'drilled_dias', 'drillz', 'pp',
  732. 'gridoffsety', 'gridx', 'gridy', 'has_offset', 'holes', 'margin', 'method',
  733. 'milled_dias',
  734. 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order', 'outname',
  735. 'overlap', 'passes', 'postamble', 'ppname_e', 'ppname_g', 'preamble', 'radius', 'ref',
  736. 'rest', 'rows', 'scale_factor', 'spacing_columns', 'spacing_rows', 'spindlespeed',
  737. 'use_threads', 'value', 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move',
  738. 'default', 'feedrate_z', 'grbl_11', 'grbl_laser', 'hpgl', 'line_xyz', 'marlin',
  739. 'Paste_1', 'Repetier', 'Toolchange_Custom', 'Roland_MDX_20', 'Toolchange_manual',
  740. 'Toolchange_Probe_MACH3', 'dwell', 'dwelltime', 'toolchange_xy', 'iso_type',
  741. 'Desktop', 'FlatPrj', 'FlatConfig', 'Users', 'Documents', 'My Documents', 'Marius'
  742. ],
  743. # General GUI Settings
  744. "global_hover": False,
  745. "global_selection_shape": True,
  746. "global_layout": "compact",
  747. # Gerber General
  748. "gerber_plot": True,
  749. "gerber_solid": True,
  750. "gerber_multicolored": False,
  751. "gerber_circle_steps": 128,
  752. "gerber_use_buffer_for_union": True,
  753. # Gerber Options
  754. "gerber_isotooldia": 0.00787402,
  755. "gerber_isopasses": 1,
  756. "gerber_isooverlap": 0.00393701,
  757. "gerber_milling_type": "cl",
  758. "gerber_combine_passes": False,
  759. "gerber_noncoppermargin": 0.00393701,
  760. "gerber_noncopperrounded": False,
  761. "gerber_bboxmargin": 0.00393701,
  762. "gerber_bboxrounded": False,
  763. # Gerber Advanced Options
  764. "gerber_aperture_display": False,
  765. "gerber_aperture_scale_factor": 1.0,
  766. "gerber_aperture_buffer_factor": 0.0,
  767. "gerber_follow": False,
  768. "gerber_buffering": "full",
  769. "gerber_simplification": False,
  770. "gerber_simp_tolerance": 0.0005,
  771. # Gerber Export
  772. "gerber_exp_units": 'IN',
  773. "gerber_exp_integer": 2,
  774. "gerber_exp_decimals": 4,
  775. "gerber_exp_zeros": 'L',
  776. # Gerber Editor
  777. "gerber_editor_sel_limit": 30,
  778. "gerber_editor_newcode": 10,
  779. "gerber_editor_newsize": 0.8,
  780. "gerber_editor_newtype": 'C',
  781. "gerber_editor_newdim": "0.5, 0.5",
  782. "gerber_editor_array_size": 5,
  783. "gerber_editor_lin_axis": 'X',
  784. "gerber_editor_lin_pitch": 1,
  785. "gerber_editor_lin_angle": 0.0,
  786. "gerber_editor_circ_dir": 'CW',
  787. "gerber_editor_circ_angle": 0.0,
  788. "gerber_editor_scale_f": 1.0,
  789. "gerber_editor_buff_f": 0.1,
  790. "gerber_editor_ma_low": 0.0,
  791. "gerber_editor_ma_high": 1.0,
  792. # Excellon General
  793. "excellon_plot": True,
  794. "excellon_solid": True,
  795. "excellon_format_upper_in": 2,
  796. "excellon_format_lower_in": 4,
  797. "excellon_format_upper_mm": 3,
  798. "excellon_format_lower_mm": 3,
  799. "excellon_zeros": "L",
  800. "excellon_units": "INCH",
  801. "excellon_update": True,
  802. "excellon_optimization_type": 'B',
  803. "excellon_search_time": 3,
  804. # Excellon Options
  805. "excellon_drillz": -0.0590551,
  806. "excellon_travelz": 0.0787402,
  807. "excellon_endz": 0.5,
  808. "excellon_feedrate": 3.14961,
  809. "excellon_spindlespeed": None,
  810. "excellon_dwell": False,
  811. "excellon_dwelltime": 1,
  812. "excellon_toolchange": False,
  813. "excellon_toolchangez": 0.5,
  814. "excellon_ppname_e": 'default',
  815. "excellon_tooldia": 0.0314961,
  816. "excellon_slot_tooldia": 0.0708661,
  817. "excellon_gcode_type": "drills",
  818. # Excellon Advanced Options
  819. "excellon_offset": 0.0,
  820. "excellon_toolchangexy": "0.0, 0.0",
  821. "excellon_startz": None,
  822. "excellon_feedrate_rapid": 31.4961,
  823. "excellon_z_pdepth": -0.02,
  824. "excellon_feedrate_probe": 3.14961,
  825. "excellon_spindledir": 'CW',
  826. "excellon_f_plunge": False,
  827. "excellon_f_retract": False,
  828. # Excellon Export
  829. "excellon_exp_units": 'INCH',
  830. "excellon_exp_format": 'ndec',
  831. "excellon_exp_integer": 2,
  832. "excellon_exp_decimals": 4,
  833. "excellon_exp_zeros": 'LZ',
  834. "excellon_exp_slot_type": 'routing',
  835. # Excellon Editor
  836. "excellon_editor_sel_limit": 30,
  837. "excellon_editor_newdia": 0.039,
  838. "excellon_editor_array_size": 5,
  839. "excellon_editor_lin_dir": 'X',
  840. "excellon_editor_lin_pitch": 0.1,
  841. "excellon_editor_lin_angle": 0.0,
  842. "excellon_editor_circ_dir": 'CW',
  843. "excellon_editor_circ_angle": 12,
  844. # Excellon Slots
  845. "excellon_editor_slot_direction": 'X',
  846. "excellon_editor_slot_angle": 0.0,
  847. "excellon_editor_slot_length": 5.0,
  848. # Excellon Slot Array
  849. "excellon_editor_slot_array_size": 5,
  850. "excellon_editor_slot_lin_dir": 'X',
  851. "excellon_editor_slot_lin_pitch": 0.1,
  852. "excellon_editor_slot_lin_angle": 0.0,
  853. "excellon_editor_slot_circ_dir": 'CW',
  854. "excellon_editor_slot_circ_angle": 0.0,
  855. # Geometry General
  856. "geometry_plot": True,
  857. "geometry_circle_steps": 128,
  858. "geometry_cnctooldia": "0.0944882",
  859. # Geometry Options
  860. "geometry_cutz": -0.0944882,
  861. "geometry_vtipdia": 0.1,
  862. "geometry_vtipangle": 30,
  863. "geometry_multidepth": False,
  864. "geometry_depthperpass": 0.0314961,
  865. "geometry_travelz": 0.0787402,
  866. "geometry_toolchange": False,
  867. "geometry_toolchangez": 0.5,
  868. "geometry_endz": 0.5,
  869. "geometry_feedrate": 3.14961,
  870. "geometry_feedrate_z": 3.14961,
  871. "geometry_spindlespeed": None,
  872. "geometry_dwell": False,
  873. "geometry_dwelltime": 1,
  874. "geometry_ppname_g": 'default',
  875. # Geometry Advanced Options
  876. "geometry_toolchangexy": "0.0, 0.0",
  877. "geometry_startz": None,
  878. "geometry_feedrate_rapid": 3.14961,
  879. "geometry_extracut": False,
  880. "geometry_z_pdepth": -0.02,
  881. "geometry_f_plunge": False,
  882. "geometry_spindledir": 'CW',
  883. "geometry_feedrate_probe": 3.14961,
  884. "geometry_segx": 0.0,
  885. "geometry_segy": 0.0,
  886. # Geometry Editor
  887. "geometry_editor_sel_limit": 30,
  888. # CNC Job General
  889. "cncjob_plot": True,
  890. "cncjob_plot_kind": 'all',
  891. "cncjob_annotation": True,
  892. "cncjob_tooldia": 0.0393701,
  893. "cncjob_coords_type": "G90",
  894. "cncjob_coords_decimals": 4,
  895. "cncjob_fr_decimals": 2,
  896. "cncjob_steps_per_circle": 128,
  897. # CNC Job Options
  898. "cncjob_prepend": "",
  899. "cncjob_append": "",
  900. # CNC Job Advanced Options
  901. "cncjob_toolchange_macro": "",
  902. "cncjob_toolchange_macro_enable": False,
  903. "cncjob_annotation_fontsize": 9,
  904. "cncjob_annotation_fontcolor": '#990000',
  905. # NCC Tool
  906. "tools_ncctools": "0.0393701, 0.019685",
  907. "tools_nccorder": 'rev',
  908. "tools_nccoverlap": 0.015748,
  909. "tools_nccmargin": 0.0393701,
  910. "tools_nccmethod": "seed",
  911. "tools_nccconnect": True,
  912. "tools_ncccontour": True,
  913. "tools_nccrest": False,
  914. "tools_ncc_offset_choice": False,
  915. "tools_ncc_offset_value": 0.0000,
  916. "tools_nccref": 'itself',
  917. "tools_ncc_plotting": 'normal',
  918. "tools_nccmilling_type": 'cl',
  919. "tools_ncctool_type": 'V',
  920. "tools_ncccutz": -0.001968504,
  921. "tools_ncctipdia": 0.00393701,
  922. "tools_ncctipangle": 30,
  923. # Cutout Tool
  924. "tools_cutouttooldia": 0.0944882,
  925. "tools_cutoutkind": "single",
  926. "tools_cutoutmargin": 0.00393701,
  927. "tools_cutoutgapsize": 0.15748,
  928. "tools_gaps_ff": "4",
  929. "tools_cutout_convexshape": False,
  930. # Paint Tool
  931. "tools_painttooldia": 0.023622,
  932. "tools_paintorder": 'rev',
  933. "tools_paintoverlap": 0.015748,
  934. "tools_paintmargin": 0.0,
  935. "tools_paintmethod": "seed",
  936. "tools_selectmethod": "single",
  937. "tools_pathconnect": True,
  938. "tools_paintcontour": True,
  939. "tools_paint_plotting": 'normal',
  940. # 2-Sided Tool
  941. "tools_2sided_mirror_axis": "X",
  942. "tools_2sided_axis_loc": "point",
  943. "tools_2sided_drilldia": 0.0393701,
  944. # Film Tool
  945. "tools_film_type": 'neg',
  946. "tools_film_boundary": 0.0393701,
  947. "tools_film_scale": 0,
  948. "tools_film_color": '#000000',
  949. # Panel Tool
  950. "tools_panelize_spacing_columns": 0,
  951. "tools_panelize_spacing_rows": 0,
  952. "tools_panelize_columns": 1,
  953. "tools_panelize_rows": 1,
  954. "tools_panelize_constrain": False,
  955. "tools_panelize_constrainx": 0.0,
  956. "tools_panelize_constrainy": 0.0,
  957. "tools_panelize_panel_type": 'gerber',
  958. # Calculators Tool
  959. "tools_calc_vshape_tip_dia": 0.007874,
  960. "tools_calc_vshape_tip_angle": 30,
  961. "tools_calc_vshape_cut_z": 0.000787,
  962. "tools_calc_electro_length": 10.0,
  963. "tools_calc_electro_width": 10.0,
  964. "tools_calc_electro_cdensity": 13.0,
  965. "tools_calc_electro_growth": 10.0,
  966. # Transform Tool
  967. "tools_transform_rotate": 90,
  968. "tools_transform_skew_x": 0.0,
  969. "tools_transform_skew_y": 0.0,
  970. "tools_transform_scale_x": 1.0,
  971. "tools_transform_scale_y": 1.0,
  972. "tools_transform_scale_link": True,
  973. "tools_transform_scale_reference": True,
  974. "tools_transform_offset_x": 0.0,
  975. "tools_transform_offset_y": 0.0,
  976. "tools_transform_mirror_reference": False,
  977. "tools_transform_mirror_point": (0, 0),
  978. # SolderPaste Tool
  979. "tools_solderpaste_tools": "0.0393701, 0.011811",
  980. "tools_solderpaste_new": 0.011811,
  981. "tools_solderpaste_z_start": 0.00019685039,
  982. "tools_solderpaste_z_dispense": 0.00393701,
  983. "tools_solderpaste_z_stop": 0.00019685039,
  984. "tools_solderpaste_z_travel": 0.00393701,
  985. "tools_solderpaste_z_toolchange": 0.0393701,
  986. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  987. "tools_solderpaste_frxy": 3.0,
  988. "tools_solderpaste_frz": 3.0,
  989. "tools_solderpaste_frz_dispense": 0.0393701,
  990. "tools_solderpaste_speedfwd": 20,
  991. "tools_solderpaste_dwellfwd": 1,
  992. "tools_solderpaste_speedrev": 10,
  993. "tools_solderpaste_dwellrev": 1,
  994. "tools_solderpaste_pp": 'Paste_1',
  995. # Subtract Tool
  996. "tools_sub_close_paths": True,
  997. # file associations
  998. "fa_excellon": ".drl, .xln, .drd, .tap, .exc, .ncd",
  999. "fa_gcode": ".nc, .ncc, .tap, .gcode, .cnc, .ecs, .fnc, .dnc, .ncg, .gc, .fan, .fgc, .din, .xpi,"
  1000. " .hnc, .h, .i, .ncp, .min, .gcd, .rol, .mpr, .ply, .out, .eia, .plt, .sbp, .mpf",
  1001. "fa_gerber": ".gbr, .ger, .gtl, .gbl, .gts, .gbs, .gtp, .gbp, .gto, .gbo, .gm1, .gml, .gm3, .gko, .cmp, "
  1002. ".sol, .stc, .sts, .plc, .pls, .crc, .crs, .tsm, .bsm, .ly2, .ly15, .dim, .mil, .grb, .top, "
  1003. ".bot, .smt, .smb, .sst, .ssb, .spt, .spb, .pho, .gdo, .art, .gbd",
  1004. })
  1005. # ############################################################
  1006. # ############### Load defaults from file ####################
  1007. # ############################################################
  1008. if user_defaults:
  1009. self.load_defaults(filename='current_defaults')
  1010. # #############################################################
  1011. # ############## APPLY APP LANGUAGE ###########################
  1012. # #############################################################
  1013. ret_val = fcTranslate.apply_language('strings')
  1014. if ret_val == "no language":
  1015. self.inform.emit('[ERROR] %s' %
  1016. _("Could not find the Language files. The App strings are missing."))
  1017. log.debug("Could not find the Language files. The App strings are missing.")
  1018. else:
  1019. # make the current language the current selection on the language combobox
  1020. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1021. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1022. # ##############################################################
  1023. # ################# CREATE UNIQUE SERIAL NUMBER ################
  1024. # ##############################################################
  1025. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1026. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1027. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  1028. self.save_defaults(silent=True)
  1029. self.propagate_defaults(silent=True)
  1030. self.restore_main_win_geom()
  1031. def auto_save_defaults():
  1032. try:
  1033. self.save_defaults(silent=True)
  1034. self.propagate_defaults(silent=True)
  1035. finally:
  1036. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1037. # the following lines activates automatic defaults save
  1038. # if user_defaults:
  1039. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1040. # self.options_form = PreferencesUI()
  1041. self.options_form_fields = {
  1042. "units": self.ui.general_options_form.general_app_group.units_radio,
  1043. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  1044. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  1045. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  1046. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  1047. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  1048. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  1049. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  1050. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  1051. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  1052. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  1053. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  1054. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  1055. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  1056. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  1057. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  1058. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  1059. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  1060. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  1061. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1062. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1063. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  1064. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  1065. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  1066. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  1067. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  1068. "excellon_endz": self.ui.excellon_options_form.excellon_opt_group.eendz_entry,
  1069. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  1070. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  1071. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  1072. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  1073. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  1074. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  1075. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  1076. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  1077. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1078. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  1079. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  1080. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  1081. "excellon_spindledir": self.ui.excellon_options_form.excellon_adv_opt_group.spindledir_radio,
  1082. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  1083. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  1084. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  1085. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  1086. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  1087. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  1088. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  1089. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  1090. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  1091. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  1092. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  1093. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  1094. "geometry_endz": self.ui.geometry_options_form.geometry_opt_group.gendz_entry,
  1095. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  1096. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  1097. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  1098. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  1099. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1100. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  1101. "geometry_spindledir": self.ui.geometry_options_form.geometry_adv_opt_group.spindledir_radio,
  1102. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  1103. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  1104. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  1105. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  1106. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  1107. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  1108. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  1109. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  1110. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  1111. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  1112. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  1113. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  1114. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  1115. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  1116. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  1117. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  1118. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  1119. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  1120. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1121. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1122. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1123. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1124. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1125. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1126. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1127. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1128. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  1129. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1130. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1131. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1132. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1133. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1134. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1135. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1136. }
  1137. for name in list(self.postprocessors.keys()):
  1138. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1139. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1140. self.options = LoudDict()
  1141. self.options.set_change_callback(self.on_options_dict_change)
  1142. self.options.update({
  1143. "units": "IN",
  1144. "global_gridx": 1.0,
  1145. "global_gridy": 1.0,
  1146. "global_snap_max": 0.05,
  1147. "global_background_timeout": 300000, # Default value is 5 minutes
  1148. "global_verbose_error_level": 0, # Shell verbosity:
  1149. # 0 = default(python trace only for unknown errors),
  1150. # 1 = show trace(show trace allways), 2 = (For the future).
  1151. "gerber_plot": True,
  1152. "gerber_solid": True,
  1153. "gerber_multicolored": False,
  1154. "gerber_isotooldia": 0.016,
  1155. "gerber_isopasses": 1,
  1156. "gerber_isooverlap": 0.15,
  1157. "gerber_combine_passes": True,
  1158. "gerber_noncoppermargin": 0.0,
  1159. "gerber_noncopperrounded": False,
  1160. "gerber_bboxmargin": 0.0,
  1161. "gerber_bboxrounded": False,
  1162. "excellon_plot": True,
  1163. "excellon_solid": False,
  1164. "excellon_format_upper_in": 2,
  1165. "excellon_format_lower_in": 4,
  1166. "excellon_format_upper_mm": 3,
  1167. "excellon_format_lower_mm": 3,
  1168. "excellon_units": 'INCH',
  1169. "excellon_optimization_type": 'B',
  1170. "excellon_search_time": 3,
  1171. "excellon_zeros": "L",
  1172. "excellon_drillz": -0.1,
  1173. "excellon_travelz": 0.1,
  1174. "excellon_feedrate": 3.0,
  1175. "excellon_feedrate_rapid": 3.0,
  1176. "excellon_spindlespeed": None,
  1177. "excellon_spindledir": 'CW',
  1178. "excellon_dwell": True,
  1179. "excellon_dwelltime": 1000,
  1180. "excellon_toolchange": False,
  1181. "excellon_toolchangez": 1.0,
  1182. "excellon_toolchangexy": "0.0, 0.0",
  1183. "excellon_tooldia": 0.016,
  1184. "excellon_ppname_e": 'default',
  1185. "excellon_f_plunge": False,
  1186. "excellon_startz": None,
  1187. "excellon_endz": 2.0,
  1188. "geometry_plot": True,
  1189. "geometry_segx": 0.0,
  1190. "geometry_segy": 0.0,
  1191. "geometry_cutz": -0.002,
  1192. "geometry_vtipdia": 0.1,
  1193. "geometry_vtipangle": 30,
  1194. "geometry_travelz": 0.1,
  1195. "geometry_feedrate": 3.0,
  1196. "geometry_feedrate_z": 3.0,
  1197. "geometry_feedrate_rapid": 3.0,
  1198. "geometry_spindlespeed": None,
  1199. "geometry_spindledir": 'CW',
  1200. "geometry_dwell": True,
  1201. "geometry_dwelltime": 1000,
  1202. "geometry_cnctooldia": 0.016,
  1203. "geometry_toolchange": False,
  1204. "geometry_toolchangez": 2.0,
  1205. "geometry_toolchangexy": "0.0, 0.0",
  1206. "geometry_startz": None,
  1207. "geometry_endz": 2.0,
  1208. "geometry_ppname_g": "default",
  1209. "geometry_f_plunge": False,
  1210. "geometry_depthperpass": 0.002,
  1211. "geometry_multidepth": False,
  1212. "geometry_extracut": False,
  1213. "cncjob_plot": True,
  1214. "cncjob_tooldia": 0.016,
  1215. "cncjob_prepend": "",
  1216. "cncjob_append": "",
  1217. "tools_ncctools": "1.0, 0.5",
  1218. "tools_nccoverlap": 0.4,
  1219. "tools_nccmargin": 1,
  1220. "tools_cutouttooldia": 0.07,
  1221. "tools_cutoutmargin": 0.1,
  1222. "tools_cutoutgapsize": 0.15,
  1223. "tools_gaps_ff": "8",
  1224. "tools_painttooldia": 0.07,
  1225. "tools_paintoverlap": 0.15,
  1226. "tools_paintmargin": 0.0,
  1227. "tools_paintmethod": "seed",
  1228. "tools_selectmethod": "single",
  1229. "tools_pathconnect": True,
  1230. "tools_paintcontour": True,
  1231. "tools_2sided_mirror_axis": "X",
  1232. "tools_2sided_axis_loc": 'point',
  1233. "tools_2sided_drilldia": 1,
  1234. "tools_film_type": 'neg',
  1235. "tools_film_boundary": 1,
  1236. "tools_film_scale": 0,
  1237. "tools_panelize_spacing_columns": 0,
  1238. "tools_panelize_spacing_rows": 0,
  1239. "tools_panelize_columns": 1,
  1240. "tools_panelize_rows": 1,
  1241. "tools_panelize_constrain": False,
  1242. "tools_panelize_constrainx": 0.0,
  1243. "tools_panelize_constrainy": 0.0
  1244. })
  1245. self.options.update(self.defaults) # Copy app defaults to project options
  1246. self.gen_form = None
  1247. self.ger_form = None
  1248. self.exc_form = None
  1249. self.geo_form = None
  1250. self.cnc_form = None
  1251. self.tools_form = None
  1252. self.fa_form = None
  1253. self.on_options_combo_change(0) # Will show the initial form
  1254. # ################################
  1255. # ### Initialize the color box's color in Preferences -> Global -> Color
  1256. # Init Plot Colors
  1257. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1258. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1259. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1260. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1261. int(self.defaults['global_plot_fill'][7:9], 16))
  1262. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1263. int(self.defaults['global_plot_fill'][7:9], 16))
  1264. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1265. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1266. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1267. # Init Left-Right Selection colors
  1268. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1269. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1270. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1271. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1272. int(self.defaults['global_sel_fill'][7:9], 16))
  1273. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1274. int(self.defaults['global_sel_fill'][7:9], 16))
  1275. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1276. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1277. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1278. # Init Right-Left Selection colors
  1279. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1280. self.defaults['global_alt_sel_fill'])
  1281. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1282. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1283. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1284. int(self.defaults['global_sel_fill'][7:9], 16))
  1285. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1286. int(self.defaults['global_sel_fill'][7:9], 16))
  1287. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1288. self.defaults['global_alt_sel_line'])
  1289. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1290. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1291. # Init Draw color and Selection Draw Color
  1292. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1293. self.defaults['global_draw_color'])
  1294. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1295. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1296. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1297. self.defaults['global_sel_draw_color'])
  1298. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1299. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1300. # Init Project Items color
  1301. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1302. self.defaults['global_proj_item_color'])
  1303. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1304. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1305. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1306. self.defaults['global_proj_item_dis_color'])
  1307. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1308. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1309. # Init the Annotation CNC Job color
  1310. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  1311. self.defaults['cncjob_annotation_fontcolor'])
  1312. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  1313. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1314. # Init the Tool Film color
  1315. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  1316. self.defaults['tools_film_color'])
  1317. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  1318. "background-color:%s" % str(self.defaults['tools_film_color'])[:7])
  1319. # ### End of Data ####
  1320. # ###############################################
  1321. # ############# SETUP Plot Area #################
  1322. # ###############################################
  1323. if show_splash:
  1324. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1325. "Canvas initialization started."),
  1326. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1327. color=QtGui.QColor("gray"))
  1328. start_plot_time = time.time() # debug
  1329. self.plotcanvas = None
  1330. self.app_cursor = None
  1331. self.hover_shapes = None
  1332. self.on_plotcanvas_setup()
  1333. end_plot_time = time.time()
  1334. self.used_time = end_plot_time - start_plot_time
  1335. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1336. if show_splash:
  1337. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1338. "Canvas initialization started.\n"
  1339. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1340. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1341. color=QtGui.QColor("gray"))
  1342. self.ui.splitter.setStretchFactor(1, 2)
  1343. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1344. # depending on from where those tools are called different actions can be done
  1345. self.call_source = 'app'
  1346. # ##############################################
  1347. # ######### SETUP OBJECT COLLECTION ############
  1348. # ##############################################
  1349. self.collection = ObjectCollection(self)
  1350. self.ui.project_tab_layout.addWidget(self.collection.view)
  1351. # ### Adjust tabs width ## ##
  1352. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1353. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1354. self.collection.view.setMinimumWidth(290)
  1355. self.log.debug("Finished creating Object Collection.")
  1356. # ###############################################
  1357. # ############# Worker SETUP ####################
  1358. # ###############################################
  1359. if self.defaults["global_worker_number"]:
  1360. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1361. else:
  1362. self.workers = WorkerStack(workers_number=2)
  1363. self.worker_task.connect(self.workers.add_task)
  1364. self.log.debug("Finished creating Workers crew.")
  1365. # ################################################
  1366. # ############### Signal handling ################
  1367. # ################################################
  1368. # ############# Custom signals ##################
  1369. # signal for displaying messages in status bar
  1370. self.inform.connect(self.info)
  1371. # signal to be called when the app is quiting
  1372. self.app_quit.connect(self.quit_application)
  1373. self.message.connect(self.message_dialog)
  1374. self.progress.connect(self.set_progress_bar)
  1375. # signals that are emitted when object state changes
  1376. self.object_created.connect(self.on_object_created)
  1377. self.object_changed.connect(self.on_object_changed)
  1378. self.object_plotted.connect(self.on_object_plotted)
  1379. self.plots_updated.connect(self.on_plots_updated)
  1380. # signals emitted when file state change
  1381. self.file_opened.connect(self.register_recent)
  1382. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1383. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1384. # ############# Standard signals ###################
  1385. # ### Menu
  1386. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1387. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1388. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1389. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1390. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1391. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1392. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1393. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1394. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1395. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1396. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1397. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1398. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1399. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1400. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1401. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1402. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1403. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1404. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1405. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1406. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1407. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1408. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1409. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1410. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1411. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1412. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1413. self.ui.menufile_exit.triggered.connect(self.final_save)
  1414. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1415. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1416. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1417. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1418. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1419. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1420. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1421. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1422. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1423. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1424. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1425. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1426. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1427. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1428. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1429. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1430. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1431. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1432. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1433. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1434. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1435. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1436. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1437. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1438. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1439. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1440. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1441. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1442. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1443. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1444. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1445. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1446. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1447. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1448. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1449. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1450. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1451. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1452. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1453. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1454. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1455. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1456. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1457. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1458. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1459. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1460. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1461. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1462. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1463. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1464. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1465. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1466. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1467. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1468. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1469. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1470. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1471. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1472. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1473. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1474. # ToolBar signals
  1475. self.connect_toolbar_signals()
  1476. # Notebook signals
  1477. # make the right click on the notebook tab connect to a function
  1478. self.ui.notebook.setupContextMenu()
  1479. self.ui.notebook.addContextMenu(
  1480. _("Detachable Tabs"), self.on_notebook_tab_rmb_click,
  1481. initial_checked=self.defaults["global_tabs_detachable"])
  1482. # activate initial state
  1483. self.on_notebook_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1484. # Context Menu
  1485. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1486. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1487. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1488. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1489. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1490. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1491. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1492. self.ui.clearplot.triggered.connect(self.clear_plots)
  1493. self.ui.replot.triggered.connect(self.plot_all)
  1494. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1495. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1496. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1497. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1498. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1499. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1500. # Preferences Plot Area TAB
  1501. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1502. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1503. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1504. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1505. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1506. # ##############################
  1507. # ### GUI PREFERENCES SIGNALS ##
  1508. # ##############################
  1509. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1510. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1511. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1512. )
  1513. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1514. lambda: self.on_toggle_units(no_pref=False))
  1515. # ###############################################################
  1516. # ################### GUI COLORS SIGNALS ########################
  1517. # ###############################################################
  1518. # Setting plot colors signals
  1519. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1520. self.on_pf_color_entry)
  1521. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1522. self.on_pf_color_button)
  1523. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1524. self.on_pf_color_spinner)
  1525. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1526. self.on_pf_color_slider)
  1527. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1528. self.on_pl_color_entry)
  1529. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1530. self.on_pl_color_button)
  1531. # Setting selection (left - right) colors signals
  1532. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1533. self.on_sf_color_entry)
  1534. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1535. self.on_sf_color_button)
  1536. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1537. self.on_sf_color_spinner)
  1538. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1539. self.on_sf_color_slider)
  1540. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1541. self.on_sl_color_entry)
  1542. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1543. self.on_sl_color_button)
  1544. # Setting selection (right - left) colors signals
  1545. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1546. self.on_alt_sf_color_entry)
  1547. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1548. self.on_alt_sf_color_button)
  1549. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1550. self.on_alt_sf_color_spinner)
  1551. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1552. self.on_alt_sf_color_slider)
  1553. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1554. self.on_alt_sl_color_entry)
  1555. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1556. self.on_alt_sl_color_button)
  1557. # Setting Editor Draw colors signals
  1558. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1559. self.on_draw_color_entry)
  1560. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1561. self.on_draw_color_button)
  1562. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1563. self.on_sel_draw_color_entry)
  1564. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1565. self.on_sel_draw_color_button)
  1566. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1567. self.on_proj_color_entry)
  1568. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1569. self.on_proj_color_button)
  1570. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1571. self.on_proj_color_dis_entry)
  1572. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1573. self.on_proj_color_dis_button)
  1574. # ########## workspace setting signals ###########
  1575. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1576. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1577. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1578. # ########## CNC Job related signals #############
  1579. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1580. self.on_cnc_custom_parameters)
  1581. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1582. self.on_annotation_fontcolor_entry)
  1583. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1584. self.on_annotation_fontcolor_button)
  1585. # ########## Tools related signals #############
  1586. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1587. self.on_film_color_entry)
  1588. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1589. self.on_film_color_button)
  1590. # ########## Modify G-CODE Plot Area TAB ###########
  1591. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1592. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1593. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1594. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1595. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1596. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1597. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1598. # portability changed signal
  1599. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1600. # Object list
  1601. self.collection.view.activated.connect(self.on_row_activated)
  1602. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1603. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1604. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1605. # Export Excellon parameters.
  1606. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1607. self.on_update_exc_export
  1608. )
  1609. # call it once to make sure it is updated at startup
  1610. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1611. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1612. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1613. self.on_excellon_defaults_button)
  1614. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1615. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1616. self.on_excellon_options_button)
  1617. # when there are arguments at application startup this get launched
  1618. self.args_at_startup[list].connect(self.on_startup_args)
  1619. # connect the 'Apply' buttons from the Preferences/File Associations
  1620. self.ui.fa_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1621. lambda: self.on_register_files(obj_type='excellon'))
  1622. self.ui.fa_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1623. lambda: self.on_register_files(obj_type='gcode'))
  1624. self.ui.fa_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1625. lambda: self.on_register_files(obj_type='gerber'))
  1626. # splash screen button signal
  1627. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1628. # connect the abort_all_tasks related slots to the related signals
  1629. self.proc_container.idle_flag.connect(self.app_is_idle)
  1630. # #####################################################################################
  1631. # ########### FINISHED CONNECTING SIGNALS #############################################
  1632. # #####################################################################################
  1633. self.log.debug("Finished connecting Signals.")
  1634. # #####################################################################################
  1635. # ########################## Other setups #############################################
  1636. # #####################################################################################
  1637. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1638. self.tool_tab_locked = False
  1639. # decide if to show or hide the Notebook side of the screen at startup
  1640. if self.defaults["global_project_at_startup"] is True:
  1641. self.ui.splitter.setSizes([1, 1])
  1642. else:
  1643. self.ui.splitter.setSizes([0, 1])
  1644. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1645. self.setup_obj_classes()
  1646. self.setup_recent_items()
  1647. self.setup_component_editor()
  1648. # #####################################################################################
  1649. # ######################### Auto-complete KEYWORDS ####################################
  1650. # #####################################################################################
  1651. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1652. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1653. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1654. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1655. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1656. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1657. 'mirror', 'ncc',
  1658. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1659. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'paint',
  1660. 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'save', 'save_project',
  1661. 'save_sys', 'scale',
  1662. 'set_active', 'set_sys', 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1663. 'version', 'write_gcode'
  1664. ]
  1665. self.ordinary_keywords = self.defaults["global_autocomplete_keywords"]
  1666. self.tcl_keywords = [
  1667. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1668. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1669. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1670. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1671. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1672. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1673. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1674. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1675. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1676. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1677. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1678. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1679. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1680. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1681. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1682. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1683. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1684. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1685. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1686. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1687. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1688. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1689. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1690. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1691. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1692. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1693. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1694. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1695. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1696. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1697. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1698. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1699. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1700. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1701. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1702. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1703. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1704. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1705. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1706. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1707. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1708. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1709. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1710. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1711. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1712. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1713. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1714. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1715. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1716. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1717. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1718. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1719. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1720. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1721. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1722. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1723. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1724. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1725. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1726. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1727. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1728. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1729. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1730. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1731. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1732. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1733. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1734. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1735. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1736. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1737. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1738. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1739. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1740. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1741. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1742. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1743. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1744. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1745. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1746. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1747. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1748. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1749. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1750. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1751. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1752. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1753. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1754. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1755. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1756. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1757. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1758. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1759. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1760. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1761. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1762. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1763. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1764. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1765. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1766. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1767. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1768. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1769. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1770. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1771. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1772. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1773. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1774. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1775. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1776. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1777. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1778. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1779. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1780. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1781. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1782. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1783. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1784. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1785. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1786. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1787. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1788. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1789. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1790. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1791. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1792. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1793. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1794. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1795. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1796. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1797. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1798. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1799. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1800. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1801. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1802. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1803. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1804. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1805. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1806. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1807. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1808. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1809. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1810. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1811. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1812. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1813. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1814. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1815. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1816. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1817. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1818. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1819. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1820. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1821. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1822. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1823. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1824. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1825. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1826. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1827. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1828. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1829. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1830. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1831. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1832. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1833. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1834. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1835. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1836. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1837. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1838. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1839. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1840. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1841. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1842. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1843. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1844. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1845. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1846. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1847. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1848. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1849. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1850. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1851. ]
  1852. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords + self.tcl_keywords
  1853. self.default_autocomplete_keywords = [
  1854. 'all', 'angle_x', 'angle_y', 'axis', 'axisoffset', 'box', 'center_x', 'center_y',
  1855. 'columns', 'combine', 'connect', 'contour', 'depthperpass', 'dia', 'diatol', 'dist',
  1856. 'drilled_dias', 'drillz', 'pp',
  1857. 'gridoffsety', 'gridx', 'gridy', 'has_offset', 'holes', 'margin', 'method',
  1858. 'milled_dias',
  1859. 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order', 'outname',
  1860. 'overlap', 'passes', 'postamble', 'ppname_e', 'ppname_g', 'preamble', 'radius', 'ref',
  1861. 'rest', 'rows', 'scale_factor', 'spacing_columns', 'spacing_rows', 'spindlespeed',
  1862. 'use_threads', 'value', 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move',
  1863. 'default', 'feedrate_z', 'grbl_11', 'grbl_laser', 'hpgl', 'line_xyz', 'marlin',
  1864. 'Paste_1', 'Repetier', 'Toolchange_Custom', 'Roland_MDX_20', 'Toolchange_manual',
  1865. 'Toolchange_Probe_MACH3', 'dwell', 'dwelltime', 'toolchange_xy', 'iso_type',
  1866. 'Desktop', 'FlatPrj', 'FlatConfig', 'Users', 'Documents', 'My Documents', 'Marius'
  1867. ]
  1868. # ####################################################################################
  1869. # ####################### Shell SETUP ################################################
  1870. # ####################################################################################
  1871. self.shell = FCShell(self, version=self.version)
  1872. self.shell._edit.set_model_data(self.myKeywords)
  1873. self.ui.code_editor.set_model_data(self.myKeywords)
  1874. self.shell.setWindowIcon(self.ui.app_icon)
  1875. self.shell.setWindowTitle("FlatCAM Shell")
  1876. self.shell.resize(*self.defaults["global_shell_shape"])
  1877. self.shell.append_output("FlatCAM %s - " % self.version)
  1878. self.shell.append_output(_("Open Source Software - Type help to get started\n\n"))
  1879. self.init_tcl()
  1880. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1881. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1882. self.ui.shell_dock.setWidget(self.shell)
  1883. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1884. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1885. QtWidgets.QDockWidget.DockWidgetFloatable |
  1886. QtWidgets.QDockWidget.DockWidgetClosable)
  1887. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1888. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1889. if self.defaults["global_shell_at_startup"]:
  1890. self.ui.shell_dock.show()
  1891. else:
  1892. self.ui.shell_dock.hide()
  1893. # ##################################################################################
  1894. # ###################### Tools and Plugins #########################################
  1895. # ##################################################################################
  1896. self.dblsidedtool = None
  1897. self.measurement_tool = None
  1898. self.panelize_tool = None
  1899. self.film_tool = None
  1900. self.paste_tool = None
  1901. self.calculator_tool = None
  1902. self.sub_tool = None
  1903. self.move_tool = None
  1904. self.cutout_tool = None
  1905. self.ncclear_tool = None
  1906. self.paint_tool = None
  1907. self.transform_tool = None
  1908. self.properties_tool = None
  1909. self.pdf_tool = None
  1910. self.image_tool = None
  1911. self.pcb_wizard_tool = None
  1912. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1913. self.install_tools()
  1914. # ### System Font Parsing ###
  1915. # self.f_parse = ParseFont(self)
  1916. # self.parse_system_fonts()
  1917. # #####################################################################################
  1918. # ######################## Check for updates ##########################################
  1919. # #####################################################################################
  1920. # Separate thread (Not worker)
  1921. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1922. if (self.beta is False or self.beta is None) and \
  1923. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1924. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1925. self.thr2 = QtCore.QThread()
  1926. self.worker_task.emit({'fcn': self.version_check,
  1927. 'params': []})
  1928. self.thr2.start(QtCore.QThread.LowPriority)
  1929. # #####################################################################################
  1930. # ###################### Variables for global usage ###################################
  1931. # #####################################################################################
  1932. # register files with FlatCAM; it works only for Windows for now
  1933. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1934. self.on_register_files()
  1935. # coordinates for relative position display
  1936. self.rel_point1 = (0, 0)
  1937. self.rel_point2 = (0, 0)
  1938. # variable to store coordinates
  1939. self.pos = (0, 0)
  1940. self.pos_jump = (0, 0)
  1941. # variable to store mouse coordinates
  1942. self.mouse = [0, 0]
  1943. # decide if we have a double click or single click
  1944. self.doubleclick = False
  1945. # variable to store if a command is active (then the var is not None) and which one it is
  1946. self.command_active = None
  1947. # variable to store the status of moving selection action
  1948. # None value means that it's not an selection action
  1949. # True value = a selection from left to right
  1950. # False value = a selection from right to left
  1951. self.selection_type = None
  1952. # List to store the objects that are currently loaded in FlatCAM
  1953. # This list is updated on each object creation or object delete
  1954. self.all_objects_list = list()
  1955. # List to store the objects that are selected
  1956. self.sel_objects_list = list()
  1957. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1958. self.key_modifiers = None
  1959. # Variable to hold the status of the axis
  1960. self.toggle_axis = True
  1961. # Variable to store the status of the fullscreen event
  1962. self.toggle_fscreen = False
  1963. # Variable to store the status of the code editor
  1964. self.toggle_codeeditor = False
  1965. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1966. self.click_noproject = False
  1967. self.cursor = None
  1968. # Variable to store the GCODE that was edited
  1969. self.gcode_edited = ""
  1970. # reference for the self.ui.code_editor
  1971. self.reference_code_editor = None
  1972. self.script_code = ''
  1973. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  1974. self.preferences_changed_flag = False
  1975. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3',
  1976. 'gko', 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15',
  1977. 'dim', 'mil', 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo',
  1978. 'art', 'gbd', 'gb0', 'gb1', 'gb2', 'gb3', 'g4', 'gb5', 'gb6', 'gb7', 'gb8', 'gb9'
  1979. ]
  1980. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc', 'ncd']
  1981. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1982. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1983. 'mpf'
  1984. ]
  1985. self.svg_list = ['svg']
  1986. self.dxf_list = ['dxf']
  1987. self.pdf_list = ['pdf']
  1988. self.prj_list = ['flatprj']
  1989. self.conf_list = ['flatconfig']
  1990. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1991. # flag for polygons not cleared
  1992. self.poly_not_cleared = False
  1993. # VisPy visuals
  1994. self.isHovering = False
  1995. self.notHovering = True
  1996. # when True, the app has to return from any thread
  1997. self.abort_flag = False
  1998. # ###############################################################################
  1999. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2000. # ############# It's done only once after install ###############
  2001. # ###############################################################################
  2002. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2003. fac_def_from_file = factory_file.read()
  2004. factory_defaults = json.loads(fac_def_from_file)
  2005. # if the file contain an empty dictionary then save the factory defaults into the file
  2006. if not factory_defaults:
  2007. self.save_factory_defaults(silent=False)
  2008. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2009. initial_lay = 'compact'
  2010. self.on_layout(lay=initial_lay)
  2011. # Set the combobox in Preferences to the current layout
  2012. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2013. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2014. factory_file.close()
  2015. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  2016. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2017. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2018. # after the first run, this object should be False
  2019. self.defaults["first_run"] = False
  2020. # ###############################################################################
  2021. # ################# ADDING FlatCAM EDITORS section ##############################
  2022. # ###############################################################################
  2023. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2024. # at the first launch of the App , the editors will not be functional.
  2025. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2026. self.exc_editor = FlatCAMExcEditor(self)
  2027. self.grb_editor = FlatCAMGrbEditor(self)
  2028. self.log.debug("Finished adding FlatCAM Editor's.")
  2029. self.set_ui_title(name=_("New Project - Not saved"))
  2030. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2031. current_platform = platform.architecture()[0]
  2032. if current_platform != '64bit':
  2033. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2034. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2035. # ###############################################################################
  2036. # ####################### Finished the CONSTRUCTOR ##############################
  2037. # ###############################################################################
  2038. App.log.debug("END of constructor. Releasing control.")
  2039. # #####################################################################################
  2040. # ########################## START-UP ARGUMENTS #######################################
  2041. # #####################################################################################
  2042. # test if the program was started with a script as parameter
  2043. if self.cmd_line_shellfile:
  2044. try:
  2045. with open(self.cmd_line_shellfile, "r") as myfile:
  2046. if show_splash:
  2047. self.splash.showMessage('%s: %ssec\n%s' % (
  2048. _("Canvas initialization started.\n"
  2049. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2050. _("Executing Tcl Script ...")),
  2051. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2052. color=QtGui.QColor("gray"))
  2053. cmd_line_shellfile_text = myfile.read()
  2054. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2055. except Exception as ext:
  2056. print("ERROR: ", ext)
  2057. sys.exit(2)
  2058. elif self.cmd_line_shellvars:
  2059. try:
  2060. with open(self.cmd_line_shellvars, "r") as myfile:
  2061. if show_splash:
  2062. self.splash.showMessage('%s: %ssec\n%s' % (
  2063. _("Canvas initialization started.\n"
  2064. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2065. _("Reading Shell vars ...")),
  2066. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2067. color=QtGui.QColor("gray"))
  2068. cmd_line_shellvars_text = myfile.read()
  2069. for line in cmd_line_shellvars_text.splitlines():
  2070. var, __, var_value = line.partition('=')
  2071. var = var.replace(' ', '')
  2072. var_value = var_value.replace(' ', '')
  2073. command_tcl = 'set {var} {var_value}'.format(var=var, var_value=var_value)
  2074. self.shell._sysShell.exec_command(command_tcl, no_echo=True)
  2075. except Exception as ext:
  2076. print("ERROR: ", ext)
  2077. sys.exit(2)
  2078. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2079. # the path/file_name must be enclosed in quotes if it contain spaces
  2080. if App.args:
  2081. self.args_at_startup.emit(App.args)
  2082. # finish the splash
  2083. self.splash.finish(self.ui)
  2084. # #####################################################################################
  2085. # ########################## SHOW GUI #################################################
  2086. # #####################################################################################
  2087. settings = QSettings("Open Source", "FlatCAM")
  2088. if settings.contains("maximized_gui"):
  2089. maximized_ui = settings.value('maximized_gui', type=bool)
  2090. if maximized_ui is True:
  2091. self.ui.showMaximized()
  2092. else:
  2093. self.ui.show()
  2094. @staticmethod
  2095. def copy_and_overwrite(from_path, to_path):
  2096. """
  2097. From here:
  2098. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2099. :param from_path: source path
  2100. :param to_path: destination path
  2101. :return: None
  2102. """
  2103. if os.path.exists(to_path):
  2104. shutil.rmtree(to_path)
  2105. try:
  2106. shutil.copytree(from_path, to_path)
  2107. except FileNotFoundError:
  2108. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2109. shutil.copytree(from_new_path, to_path)
  2110. def on_startup_args(self, args):
  2111. """
  2112. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2113. :param args: a list containing the application args at startup
  2114. :return: None
  2115. """
  2116. if args is not None:
  2117. args_to_process = args
  2118. else:
  2119. args_to_process = App.args
  2120. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2121. for argument in args_to_process:
  2122. if '.FlatPrj' in argument:
  2123. try:
  2124. project_name = str(argument)
  2125. if project_name == "":
  2126. self.inform.emit(_("Open cancelled."))
  2127. else:
  2128. # self.open_project(project_name)
  2129. run_from_arg = True
  2130. # self.worker_task.emit({'fcn': self.open_project,
  2131. # 'params': [project_name, run_from_arg]})
  2132. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2133. except Exception as e:
  2134. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2135. elif '.FlatConfig' in argument:
  2136. try:
  2137. file_name = str(argument)
  2138. if file_name == "":
  2139. self.inform.emit(_("Open Config file failed."))
  2140. else:
  2141. run_from_arg = True
  2142. # self.worker_task.emit({'fcn': self.open_config_file,
  2143. # 'params': [file_name, run_from_arg]})
  2144. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2145. except Exception as e:
  2146. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2147. elif '.FlatScript' in argument:
  2148. try:
  2149. file_name = str(argument)
  2150. if file_name == "":
  2151. self.inform.emit(_("Open Script file failed."))
  2152. else:
  2153. # run_from_arg = True
  2154. # self.worker_task.emit({'fcn': self.open_script_file,
  2155. # 'params': [file_name, run_from_arg]})
  2156. self.on_filerunscript(name=file_name)
  2157. except Exception as e:
  2158. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2159. elif 'quit' in argument or 'exit' in argument:
  2160. log.debug("App.on_startup_args() --> Quit event.")
  2161. sys.exit()
  2162. elif 'save' in argument:
  2163. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2164. self.save_defaults()
  2165. else:
  2166. exc_list = self.ui.fa_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2167. proc_arg = argument.lower()
  2168. for ext in exc_list:
  2169. proc_ext = ext.replace(' ', '')
  2170. if proc_ext.lower() in proc_arg and proc_ext != '':
  2171. file_name = str(argument)
  2172. if file_name == "":
  2173. self.inform.emit(_("Open Excellon file failed."))
  2174. else:
  2175. self.on_fileopenexcellon(name=file_name)
  2176. return
  2177. gco_list = self.ui.fa_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2178. for ext in gco_list:
  2179. proc_ext = ext.replace(' ', '')
  2180. if proc_ext.lower() in proc_arg and proc_ext != '':
  2181. file_name = str(argument)
  2182. if file_name == "":
  2183. self.inform.emit(_("Open GCode file failed."))
  2184. else:
  2185. self.on_fileopengcode(name=file_name)
  2186. return
  2187. grb_list = self.ui.fa_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2188. for ext in grb_list:
  2189. proc_ext = ext.replace(' ', '')
  2190. if proc_ext.lower() in proc_arg and proc_ext != '':
  2191. file_name = str(argument)
  2192. if file_name == "":
  2193. self.inform.emit(_("Open Gerber file failed."))
  2194. else:
  2195. self.on_fileopengerber(name=file_name)
  2196. return
  2197. def set_ui_title(self, name):
  2198. """
  2199. Sets the title of the main window.
  2200. :param name: String that store the project path and project name
  2201. :return: None
  2202. """
  2203. self.ui.setWindowTitle('FlatCAM %s %s - %s %s' %
  2204. (self.version,
  2205. ('BETA' if self.beta else ''),
  2206. platform.architecture()[0],
  2207. name)
  2208. )
  2209. def defaults_read_form(self):
  2210. """
  2211. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2212. :return: None
  2213. """
  2214. for option in self.defaults_form_fields:
  2215. try:
  2216. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2217. except Exception as e:
  2218. log.debug("App.defaults_read_form() --> %s" % str(e))
  2219. def defaults_write_form(self, factor=None, fl_units=None):
  2220. """
  2221. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2222. self.defaults dictionary.
  2223. :param factor: will apply a factor to the values that written in the GUI elements
  2224. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2225. :return: None
  2226. """
  2227. for option in self.defaults:
  2228. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2229. # try:
  2230. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2231. # except KeyError:
  2232. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2233. # # TODO: Rethink this?
  2234. # pass
  2235. def defaults_write_form_field(self, field, factor=None, units=None):
  2236. """
  2237. Basically it is the worker in the self.defaults_write_form()
  2238. :param field: the GUI element in Preferences GUI to be updated
  2239. :param factor: factor to be applied to the field parameter
  2240. :param units: current FLatCAM measuring units
  2241. :return: None, it updates GUI elements
  2242. """
  2243. try:
  2244. if factor is None:
  2245. if units is None:
  2246. self.defaults_form_fields[field].set_value(self.defaults[field])
  2247. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2248. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=6)
  2249. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2250. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=4)
  2251. else:
  2252. if units is None:
  2253. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2254. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2255. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=6)
  2256. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2257. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=4)
  2258. except KeyError:
  2259. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2260. # TODO: Rethink this?
  2261. pass
  2262. except AttributeError:
  2263. log.debug(field)
  2264. def clear_pool(self):
  2265. """
  2266. Clear the multiprocessing pool and calls garbage collector.
  2267. :return: None
  2268. """
  2269. self.pool.close()
  2270. self.pool = Pool()
  2271. self.pool_recreated.emit(self.pool)
  2272. gc.collect()
  2273. def install_tools(self):
  2274. """
  2275. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2276. Instantiation of the Tools classes.
  2277. The order that the tools are installed is important as they can depend on each other install position.
  2278. :return: None
  2279. """
  2280. self.dblsidedtool = DblSidedTool(self)
  2281. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2282. self.measurement_tool = Measurement(self)
  2283. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  2284. self.panelize_tool = Panelize(self)
  2285. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  2286. self.film_tool = Film(self)
  2287. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2288. self.paste_tool = SolderPaste(self)
  2289. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2290. self.calculator_tool = ToolCalculator(self)
  2291. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'), separator=True)
  2292. self.sub_tool = ToolSub(self)
  2293. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2294. self.move_tool = ToolMove(self)
  2295. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2296. before=self.ui.menueditorigin)
  2297. self.cutout_tool = CutOut(self)
  2298. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2299. before=self.measurement_tool.menuAction)
  2300. self.ncclear_tool = NonCopperClear(self)
  2301. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2302. before=self.measurement_tool.menuAction, separator=True)
  2303. self.paint_tool = ToolPaint(self)
  2304. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2305. before=self.measurement_tool.menuAction, separator=True)
  2306. self.transform_tool = ToolTransform(self)
  2307. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2308. self.properties_tool = Properties(self)
  2309. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2310. self.pdf_tool = ToolPDF(self)
  2311. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2312. separator=True)
  2313. self.image_tool = ToolImage(self)
  2314. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2315. separator=True)
  2316. self.pcb_wizard_tool = PcbWizard(self)
  2317. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2318. self.log.debug("Tools are installed.")
  2319. def remove_tools(self):
  2320. """
  2321. Will remove all the actions in the Tool menu.
  2322. :return: None
  2323. """
  2324. for act in self.ui.menutool.actions():
  2325. self.ui.menutool.removeAction(act)
  2326. def init_tools(self):
  2327. """
  2328. Initialize the Tool tab in the notebook side of the central widget.
  2329. Remove the actions in the Tools menu.
  2330. Instantiate again the FlatCAM tools (plugins).
  2331. All this is required when changing the layout: standard, compact etc.
  2332. :return: None
  2333. """
  2334. log.debug("init_tools()")
  2335. # delete the data currently in the Tools Tab and the Tab itself
  2336. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2337. if widget is not None:
  2338. widget.deleteLater()
  2339. self.ui.notebook.removeTab(2)
  2340. # rebuild the Tools Tab
  2341. self.ui.tool_tab = QtWidgets.QWidget()
  2342. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2343. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2344. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2345. self.ui.tool_scroll_area = VerticalScrollArea()
  2346. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2347. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2348. # first remove all of them
  2349. self.remove_tools()
  2350. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2351. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2352. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2353. # third install all of them
  2354. self.install_tools()
  2355. self.log.debug("Tools are initialized.")
  2356. # def parse_system_fonts(self):
  2357. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2358. # 'params': []})
  2359. def connect_toolbar_signals(self):
  2360. """
  2361. Reconnect the signals to the actions in the toolbar.
  2362. This has to be done each time after the FlatCAM tools are removed/installed.
  2363. :return: None
  2364. """
  2365. # Toolbar
  2366. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2367. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2368. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2369. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2370. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2371. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2372. self.ui.replot_btn.triggered.connect(self.plot_all)
  2373. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2374. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2375. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2376. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2377. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2378. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2379. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2380. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2381. self.ui.delete_btn.triggered.connect(self.on_delete)
  2382. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2383. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2384. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2385. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2386. # Tools Toolbar Signals
  2387. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2388. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2389. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2390. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2391. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2392. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2393. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2394. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2395. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2396. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2397. def object2editor(self):
  2398. """
  2399. Send the current Geometry or Excellon object (if any) into the it's editor.
  2400. :return: None
  2401. """
  2402. self.report_usage("object2editor()")
  2403. edited_object = self.collection.get_active()
  2404. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2405. isinstance(edited_object, FlatCAMExcellon):
  2406. pass
  2407. else:
  2408. self.inform.emit('[WARNING_NOTCL] %s' %
  2409. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2410. return
  2411. if isinstance(edited_object, FlatCAMGeometry):
  2412. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2413. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2414. # we set the notebook to hidden
  2415. self.ui.splitter.setSizes([0, 1])
  2416. if edited_object.multigeo is True:
  2417. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2418. if len(edited_tools) > 1:
  2419. self.inform.emit('[WARNING_NOTCL] %s' %
  2420. _("Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2421. "is not possible.\n"
  2422. "Edit only one geometry at a time."))
  2423. # determine the tool dia of the selected tool
  2424. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2425. # now find the key in the edited_object.tools that has this tooldia
  2426. multi_tool = 1
  2427. for tool in edited_object.tools:
  2428. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2429. multi_tool = tool
  2430. break
  2431. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2432. else:
  2433. self.geo_editor.edit_fcgeometry(edited_object)
  2434. # set call source to the Editor we go into
  2435. self.call_source = 'geo_editor'
  2436. elif isinstance(edited_object, FlatCAMExcellon):
  2437. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2438. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2439. if self.ui.splitter.sizes()[0] == 0:
  2440. self.ui.splitter.setSizes([1, 1])
  2441. self.exc_editor.edit_fcexcellon(edited_object)
  2442. # set call source to the Editor we go into
  2443. self.call_source = 'exc_editor'
  2444. elif isinstance(edited_object, FlatCAMGerber):
  2445. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2446. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2447. if self.ui.splitter.sizes()[0] == 0:
  2448. self.ui.splitter.setSizes([1, 1])
  2449. self.grb_editor.edit_fcgerber(edited_object)
  2450. # set call source to the Editor we go into
  2451. self.call_source = 'grb_editor'
  2452. # make sure that we can't select another object while in Editor Mode:
  2453. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2454. self.ui.project_frame.setDisabled(True)
  2455. # delete any selection shape that might be active as they are not relevant in Editor
  2456. self.delete_selection_shape()
  2457. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2458. self.ui.plot_tab_area.protectTab(0)
  2459. self.inform.emit('[WARNING_NOTCL] %s' %
  2460. _("Editor is activated ..."))
  2461. self.should_we_save = True
  2462. def editor2object(self, cleanup=None):
  2463. """
  2464. Transfers the Geometry or Excellon from it's editor to the current object.
  2465. :return: None
  2466. """
  2467. self.report_usage("editor2object()")
  2468. # do not update a geometry or excellon object unless it comes out of an editor
  2469. if self.call_source != 'app':
  2470. edited_obj = self.collection.get_active()
  2471. if cleanup is None:
  2472. msgbox = QtWidgets.QMessageBox()
  2473. msgbox.setText(_("Do you want to save the edited object?"))
  2474. msgbox.setWindowTitle(_("Close Editor"))
  2475. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2476. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2477. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2478. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2479. msgbox.setDefaultButton(bt_yes)
  2480. msgbox.exec_()
  2481. response = msgbox.clickedButton()
  2482. if response == bt_yes:
  2483. # clean the Tools Tab
  2484. self.ui.tool_scroll_area.takeWidget()
  2485. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2486. self.ui.notebook.setTabText(2, "Tool")
  2487. if isinstance(edited_obj, FlatCAMGeometry):
  2488. obj_type = "Geometry"
  2489. if cleanup is None:
  2490. self.geo_editor.update_fcgeometry(edited_obj)
  2491. self.geo_editor.update_options(edited_obj)
  2492. self.geo_editor.deactivate()
  2493. # update the geo object options so it is including the bounding box values
  2494. try:
  2495. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2496. edited_obj.options['xmin'] = xmin
  2497. edited_obj.options['ymin'] = ymin
  2498. edited_obj.options['xmax'] = xmax
  2499. edited_obj.options['ymax'] = ymax
  2500. except AttributeError as e:
  2501. self.inform.emit('[WARNING] %s' %
  2502. _("Object empty after edit."))
  2503. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2504. elif isinstance(edited_obj, FlatCAMGerber):
  2505. obj_type = "Gerber"
  2506. if cleanup is None:
  2507. self.grb_editor.update_fcgerber()
  2508. self.grb_editor.update_options(edited_obj)
  2509. self.grb_editor.deactivate_grb_editor()
  2510. # delete the old object (the source object) if it was an empty one
  2511. if len(edited_obj.solid_geometry) == 0:
  2512. old_name = edited_obj.options['name']
  2513. self.collection.set_active(old_name)
  2514. self.collection.delete_active()
  2515. elif isinstance(edited_obj, FlatCAMExcellon):
  2516. obj_type = "Excellon"
  2517. if cleanup is None:
  2518. self.exc_editor.update_fcexcellon(edited_obj)
  2519. self.exc_editor.update_options(edited_obj)
  2520. self.exc_editor.deactivate()
  2521. else:
  2522. self.inform.emit('[WARNING_NOTCL] %s' %
  2523. _("Select a Gerber, Geometry or Excellon Object to update."))
  2524. return
  2525. self.inform.emit('[selected] %s %s' %
  2526. (obj_type, _("is updated, returning to App...")))
  2527. elif response == bt_no:
  2528. # clean the Tools Tab
  2529. self.ui.tool_scroll_area.takeWidget()
  2530. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2531. self.ui.notebook.setTabText(2, "Tool")
  2532. if isinstance(edited_obj, FlatCAMGeometry):
  2533. self.geo_editor.deactivate()
  2534. elif isinstance(edited_obj, FlatCAMGerber):
  2535. self.grb_editor.deactivate_grb_editor()
  2536. elif isinstance(edited_obj, FlatCAMExcellon):
  2537. self.exc_editor.deactivate()
  2538. # set focus on the project tab
  2539. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  2540. else:
  2541. self.inform.emit('[WARNING_NOTCL] %s' %
  2542. _("Select a Gerber, Geometry or Excellon Object to update."))
  2543. return
  2544. elif response == bt_cancel:
  2545. return
  2546. else:
  2547. if isinstance(edited_obj, FlatCAMGeometry):
  2548. self.geo_editor.deactivate()
  2549. elif isinstance(edited_obj, FlatCAMGerber):
  2550. self.grb_editor.deactivate_grb_editor()
  2551. elif isinstance(edited_obj, FlatCAMExcellon):
  2552. self.exc_editor.deactivate()
  2553. else:
  2554. self.inform.emit('[WARNING_NOTCL] %s' %
  2555. _("Select a Gerber, Geometry or Excellon Object to update."))
  2556. return
  2557. # if notebook is hidden we show it
  2558. if self.ui.splitter.sizes()[0] == 0:
  2559. self.ui.splitter.setSizes([1, 1])
  2560. # restore the call_source to app
  2561. self.call_source = 'app'
  2562. edited_obj.plot()
  2563. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2564. self.ui.plot_tab_area.protectTab(0)
  2565. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2566. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2567. self.ui.project_frame.setDisabled(False)
  2568. def get_last_folder(self):
  2569. """
  2570. Get the folder path from where the last file was opened.
  2571. :return: String, last opened folder path
  2572. """
  2573. return self.defaults["global_last_folder"]
  2574. def get_last_save_folder(self):
  2575. """
  2576. Get the folder path from where the last file was saved.
  2577. :return: String, last saved folder path
  2578. """
  2579. loc = self.defaults["global_last_save_folder"]
  2580. if loc is None:
  2581. loc = self.defaults["global_last_folder"]
  2582. if loc is None:
  2583. loc = os.path.dirname(__file__)
  2584. return loc
  2585. def report_usage(self, resource):
  2586. """
  2587. Increments usage counter for the given resource
  2588. in self.defaults['global_stats'].
  2589. :param resource: Name of the resource.
  2590. :return: None
  2591. """
  2592. if resource in self.defaults['global_stats']:
  2593. self.defaults['global_stats'][resource] += 1
  2594. else:
  2595. self.defaults['global_stats'][resource] = 1
  2596. def init_tcl(self):
  2597. """
  2598. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2599. :return: None
  2600. """
  2601. if hasattr(self, 'tcl'):
  2602. # self.tcl = None
  2603. # TODO we need to clean non default variables and procedures here
  2604. # new object cannot be used here as it will not remember values created for next passes,
  2605. # because tcl was execudted in old instance of TCL
  2606. pass
  2607. else:
  2608. self.tcl = tk.Tcl()
  2609. self.setup_shell()
  2610. self.log.debug("TCL Shell has been initialized.")
  2611. # TODO: This shouldn't be here.
  2612. class TclErrorException(Exception):
  2613. """
  2614. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2615. """
  2616. pass
  2617. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2618. """
  2619. Shows a message on the FlatCAM Shell
  2620. :param msg: Message to display.
  2621. :param show: Opens the shell.
  2622. :param error: Shows the message as an error.
  2623. :param warning: Shows the message as an warning.
  2624. :param success: Shows the message as an success.
  2625. :param selected: Indicate that something was selected on canvas
  2626. :return: None
  2627. """
  2628. if show:
  2629. self.ui.shell_dock.show()
  2630. try:
  2631. if error:
  2632. self.shell.append_error(msg + "\n")
  2633. elif warning:
  2634. self.shell.append_warning(msg + "\n")
  2635. elif success:
  2636. self.shell.append_success(msg + "\n")
  2637. elif selected:
  2638. self.shell.append_selected(msg + "\n")
  2639. else:
  2640. self.shell.append_output(msg + "\n")
  2641. except AttributeError:
  2642. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2643. def raise_tcl_unknown_error(self, unknownException):
  2644. """
  2645. Raise exception if is different type than TclErrorException
  2646. this is here mainly to show unknown errors inside TCL shell console.
  2647. :param unknownException:
  2648. :return:
  2649. """
  2650. if not isinstance(unknownException, self.TclErrorException):
  2651. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2652. else:
  2653. raise unknownException
  2654. def display_tcl_error(self, error, error_info=None):
  2655. """
  2656. Escape bracket [ with '\' otherwise there is error
  2657. "ERROR: missing close-bracket" instead of real error
  2658. :param error: it may be text or exception
  2659. :param error_info: Some informations about the error
  2660. :return: None
  2661. """
  2662. if isinstance(error, Exception):
  2663. exc_type, exc_value, exc_traceback = error_info
  2664. if not isinstance(error, self.TclErrorException):
  2665. show_trace = 1
  2666. else:
  2667. show_trace = int(self.defaults['global_verbose_error_level'])
  2668. if show_trace > 0:
  2669. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2670. trc_formated = []
  2671. for a in reversed(trc):
  2672. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2673. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2674. else:
  2675. text = "%s" % error
  2676. else:
  2677. text = error
  2678. text = text.replace('[', '\\[').replace('"', '\\"')
  2679. self.tcl.eval('return -code error "%s"' % text)
  2680. def raise_tcl_error(self, text):
  2681. """
  2682. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2683. :param text: text of error
  2684. :return: raise exception
  2685. """
  2686. self.display_tcl_error(text)
  2687. raise self.TclErrorException(text)
  2688. def exec_command(self, text, no_echo=False):
  2689. """
  2690. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2691. Also handles execution in separated threads
  2692. :param text: FlatCAM TclCommand with parameters
  2693. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2694. will create crashes of the _Expandable_Edit widget
  2695. :return: output if there was any
  2696. """
  2697. self.report_usage('exec_command')
  2698. result = self.exec_command_test(text, False, no_echo=no_echo)
  2699. # MS: added this method call so the geometry is updated once the TCL command is executed
  2700. # if no_plot is None:
  2701. # self.plot_all()
  2702. return result
  2703. def exec_command_test(self, text, reraise=True, no_echo=False):
  2704. """
  2705. Same as exec_command(...) with additional control over exceptions.
  2706. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2707. :param text: Input command
  2708. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2709. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2710. will create crashes of the _Expandable_Edit widget
  2711. :return: Output from the command
  2712. """
  2713. tcl_command_string = str(text)
  2714. try:
  2715. if no_echo is False:
  2716. self.shell.open_proccessing() # Disables input box.
  2717. result = self.tcl.eval(str(tcl_command_string))
  2718. if result != 'None' and no_echo is False:
  2719. self.shell.append_output(result + '\n')
  2720. except tk.TclError as e:
  2721. # This will display more precise answer if something in TCL shell fails
  2722. result = self.tcl.eval("set errorInfo")
  2723. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2724. if no_echo is False:
  2725. self.shell.append_error('ERROR: ' + result + '\n')
  2726. # Show error in console and just return or in test raise exception
  2727. if reraise:
  2728. raise e
  2729. finally:
  2730. if no_echo is False:
  2731. self.shell.close_proccessing()
  2732. pass
  2733. return result
  2734. # """
  2735. # Code below is unsused. Saved for later.
  2736. # """
  2737. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2738. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2739. # self.log.debug(parts)
  2740. # try:
  2741. # if parts[0] not in commands:
  2742. # self.shell.append_error("Unknown command\n")
  2743. # return
  2744. #
  2745. # #import inspect
  2746. # #inspect.getargspec(someMethod)
  2747. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2748. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2749. # self.shell.append_error(
  2750. # "Command %s takes %d arguments. %d given.\n" %
  2751. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2752. # )
  2753. # return
  2754. #
  2755. # cmdfcn = commands[parts[0]]["fcn"]
  2756. # cmdconv = commands[parts[0]]["converters"]
  2757. # if len(parts) - 1 > 0:
  2758. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2759. # else:
  2760. # retval = cmdfcn()
  2761. # retfcn = commands[parts[0]]["retfcn"]
  2762. # if retval and retfcn(retval):
  2763. # self.shell.append_output(retfcn(retval) + "\n")
  2764. #
  2765. # except Exception as e:
  2766. # #self.shell.append_error(''.join(traceback.format_exc()))
  2767. # #self.shell.append_error("?\n")
  2768. # self.shell.append_error(str(e) + "\n")
  2769. def info(self, msg):
  2770. """
  2771. Informs the user. Normally on the status bar, optionally
  2772. also on the shell.
  2773. :param msg: Text to write.
  2774. :return: None
  2775. """
  2776. # Type of message in brackets at the beginning of the message.
  2777. match = re.search("\[([^\]]+)\](.*)", msg)
  2778. if match:
  2779. level = match.group(1)
  2780. msg_ = match.group(2)
  2781. self.ui.fcinfo.set_status(str(msg_), level=level)
  2782. if level.lower() == "error":
  2783. self.shell_message(msg, error=True, show=True)
  2784. elif level.lower() == "warning":
  2785. self.shell_message(msg, warning=True, show=True)
  2786. elif level.lower() == "error_notcl":
  2787. self.shell_message(msg, error=True, show=False)
  2788. elif level.lower() == "warning_notcl":
  2789. self.shell_message(msg, warning=True, show=False)
  2790. elif level.lower() == "success":
  2791. self.shell_message(msg, success=True, show=False)
  2792. elif level.lower() == "selected":
  2793. self.shell_message(msg, selected=True, show=False)
  2794. else:
  2795. self.shell_message(msg, show=False)
  2796. else:
  2797. self.ui.fcinfo.set_status(str(msg), level="info")
  2798. # make sure that if the message is to clear the infobar with a space
  2799. # is not printed over and over on the shell
  2800. if msg != '':
  2801. self.shell_message(msg)
  2802. def restore_toolbar_view(self):
  2803. """
  2804. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  2805. was saved in the defaults dictionary.
  2806. :return: None
  2807. """
  2808. tb = self.defaults["global_toolbar_view"]
  2809. if tb & 1:
  2810. self.ui.toolbarfile.setVisible(True)
  2811. else:
  2812. self.ui.toolbarfile.setVisible(False)
  2813. if tb & 2:
  2814. self.ui.toolbargeo.setVisible(True)
  2815. else:
  2816. self.ui.toolbargeo.setVisible(False)
  2817. if tb & 4:
  2818. self.ui.toolbarview.setVisible(True)
  2819. else:
  2820. self.ui.toolbarview.setVisible(False)
  2821. if tb & 8:
  2822. self.ui.toolbartools.setVisible(True)
  2823. else:
  2824. self.ui.toolbartools.setVisible(False)
  2825. if tb & 16:
  2826. self.ui.exc_edit_toolbar.setVisible(True)
  2827. else:
  2828. self.ui.exc_edit_toolbar.setVisible(False)
  2829. if tb & 32:
  2830. self.ui.geo_edit_toolbar.setVisible(True)
  2831. else:
  2832. self.ui.geo_edit_toolbar.setVisible(False)
  2833. if tb & 64:
  2834. self.ui.grb_edit_toolbar.setVisible(True)
  2835. else:
  2836. self.ui.grb_edit_toolbar.setVisible(False)
  2837. if tb & 128:
  2838. self.ui.snap_toolbar.setVisible(True)
  2839. else:
  2840. self.ui.snap_toolbar.setVisible(False)
  2841. if tb & 256:
  2842. self.ui.toolbarshell.setVisible(True)
  2843. else:
  2844. self.ui.toolbarshell.setVisible(False)
  2845. def load_defaults(self, filename):
  2846. """
  2847. Loads the aplication's default settings from current_defaults.FlatConfig into
  2848. ``self.defaults``.
  2849. :return: None
  2850. """
  2851. try:
  2852. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2853. options = f.read()
  2854. f.close()
  2855. except IOError:
  2856. self.log.error("Could not load defaults file.")
  2857. self.inform.emit('[ERROR] %s' %
  2858. _("Could not load defaults file."))
  2859. # in case the defaults file can't be loaded, show all toolbars
  2860. self.defaults["global_toolbar_view"] = 511
  2861. return
  2862. try:
  2863. defaults = json.loads(options)
  2864. except:
  2865. # in case the defaults file can't be loaded, show all toolbars
  2866. self.defaults["global_toolbar_view"] = 511
  2867. e = sys.exc_info()[0]
  2868. App.log.error(str(e))
  2869. self.inform.emit('[ERROR] %s' %
  2870. _("Failed to parse defaults file."))
  2871. return
  2872. self.defaults.update(defaults)
  2873. log.debug("FlatCAM defaults loaded from: %s" % filename)
  2874. # restore the toolbar view
  2875. self.restore_toolbar_view()
  2876. def on_import_preferences(self):
  2877. """
  2878. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  2879. ``self.defaults``.
  2880. :return: None
  2881. """
  2882. self.report_usage("on_import_preferences")
  2883. App.log.debug("on_import_preferences()")
  2884. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2885. try:
  2886. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2887. directory=self.data_path,
  2888. filter=filter_)
  2889. except TypeError:
  2890. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2891. filter=filter_)
  2892. filename = str(filename)
  2893. if filename == "":
  2894. self.inform.emit('[WARNING_NOTCL] %s' %
  2895. _("FlatCAM preferences import cancelled."))
  2896. else:
  2897. try:
  2898. f = open(filename)
  2899. options = f.read()
  2900. f.close()
  2901. except IOError:
  2902. self.log.error("Could not load defaults file.")
  2903. self.inform.emit('[ERROR_NOTCL] %s' %
  2904. _("Could not load defaults file."))
  2905. return
  2906. try:
  2907. defaults_from_file = json.loads(options)
  2908. except Exception as e:
  2909. e = sys.exc_info()[0]
  2910. App.log.error(str(e))
  2911. self.inform.emit('[ERROR_NOTCL] %s' %
  2912. _("Failed to parse defaults file."))
  2913. return
  2914. self.defaults.update(defaults_from_file)
  2915. self.on_preferences_edited()
  2916. self.inform.emit('[success] %s: %s' %
  2917. (_("Imported Defaults from"), filename))
  2918. def on_export_preferences(self):
  2919. """
  2920. Save the defaults dictionary to a file.
  2921. :return: None
  2922. """
  2923. self.report_usage("on_export_preferences")
  2924. App.log.debug("on_export_preferences()")
  2925. defaults_file_content = None
  2926. self.date = str(datetime.today()).rpartition('.')[0]
  2927. self.date = ''.join(c for c in self.date if c not in ':-')
  2928. self.date = self.date.replace(' ', '_')
  2929. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  2930. try:
  2931. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  2932. caption=_("Export FlatCAM Preferences"),
  2933. directory=self.data_path + '/preferences_' + self.date,
  2934. filter=filter__
  2935. )
  2936. except TypeError:
  2937. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  2938. filter=filter__)
  2939. filename = str(filename)
  2940. defaults_from_file = {}
  2941. if filename == "":
  2942. self.inform.emit('[WARNING_NOTCL] %s' %
  2943. _("FlatCAM preferences export cancelled."))
  2944. return
  2945. else:
  2946. try:
  2947. f = open(filename, 'w')
  2948. defaults_file_content = f.read()
  2949. f.close()
  2950. except PermissionError:
  2951. self.inform.emit('[WARNING] %s' %
  2952. _("Permission denied, saving not possible.\n"
  2953. "Most likely another app is holding the file open and not accessible."))
  2954. return
  2955. except IOError:
  2956. App.log.debug('Creating a new preferences file ...')
  2957. f = open(filename, 'w')
  2958. json.dump({}, f)
  2959. f.close()
  2960. except:
  2961. e = sys.exc_info()[0]
  2962. App.log.error("Could not load defaults file.")
  2963. App.log.error(str(e))
  2964. self.inform.emit('[ERROR_NOTCL] %s' %
  2965. _("Could not load preferences file."))
  2966. return
  2967. try:
  2968. defaults_from_file = json.loads(defaults_file_content)
  2969. except:
  2970. App.log.warning("Trying to read an empty Preferences file. Continue.")
  2971. # Update options
  2972. self.defaults_read_form()
  2973. defaults_from_file.update(self.defaults)
  2974. self.propagate_defaults(silent=True)
  2975. # Save update options
  2976. try:
  2977. f = open(filename, "w")
  2978. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  2979. f.close()
  2980. except:
  2981. self.inform.emit('[ERROR_NOTCL] %s' %
  2982. _("Failed to write defaults to file."))
  2983. return
  2984. if self.defaults["global_open_style"] is False:
  2985. self.file_opened.emit("preferences", filename)
  2986. self.file_saved.emit("preferences", filename)
  2987. self.inform.emit('[success] %s: %s' %
  2988. (_("Exported preferences to"), filename))
  2989. def on_preferences_open_folder(self):
  2990. """
  2991. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  2992. :return: None
  2993. """
  2994. self.report_usage("on_preferences_open_folder()")
  2995. if sys.platform == 'win32':
  2996. subprocess.Popen('explorer %s' % self.data_path)
  2997. elif sys.platform == 'darwin':
  2998. os.system('open "%s"' % self.data_path)
  2999. else:
  3000. subprocess.Popen(['xdg-open', self.data_path])
  3001. self.inform.emit('[success] %s' %
  3002. _("FlatCAM Preferences Folder opened."))
  3003. def save_geometry(self, x, y, width, height, notebook_width):
  3004. """
  3005. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3006. launch of the application.
  3007. :param x: X position of the main window
  3008. :param y: Y position of the main window
  3009. :param width: width of the main window
  3010. :param height: height of the main window
  3011. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3012. :return: None
  3013. """
  3014. self.defaults["global_def_win_x"] = x
  3015. self.defaults["global_def_win_y"] = y
  3016. self.defaults["global_def_win_w"] = width
  3017. self.defaults["global_def_win_h"] = height
  3018. self.defaults["global_def_notebook_width"] = notebook_width
  3019. self.save_defaults()
  3020. def message_dialog(self, title, message, kind="info"):
  3021. """
  3022. Builds and show a custom QMessageBox to be used in FlatCAM.
  3023. :param title: title of the QMessageBox
  3024. :param message: message to be displayed
  3025. :param kind: type of QMessageBox; will display a specific icon.
  3026. :return:
  3027. """
  3028. icon = {"info": QtWidgets.QMessageBox.Information,
  3029. "warning": QtWidgets.QMessageBox.Warning,
  3030. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3031. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3032. dlg.setText(message)
  3033. dlg.exec_()
  3034. def register_recent(self, kind, filename):
  3035. """
  3036. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3037. dictionary.
  3038. :param kind: type of file that was opened
  3039. :param filename: the path and file name for the file that was opened
  3040. :return:
  3041. """
  3042. self.log.debug("register_recent()")
  3043. self.log.debug(" %s" % kind)
  3044. self.log.debug(" %s" % filename)
  3045. record = {'kind': str(kind), 'filename': str(filename)}
  3046. if record in self.recent:
  3047. return
  3048. if record in self.recent_projects:
  3049. return
  3050. if record['kind'] == 'project':
  3051. self.recent_projects.insert(0, record)
  3052. else:
  3053. self.recent.insert(0, record)
  3054. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3055. self.recent.pop()
  3056. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3057. self.recent_projects.pop()
  3058. try:
  3059. f = open(self.data_path + '/recent.json', 'w')
  3060. except IOError:
  3061. App.log.error("Failed to open recent items file for writing.")
  3062. self.inform.emit('[ERROR_NOTCL] %s' %
  3063. _('Failed to open recent files file for writing.'))
  3064. return
  3065. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3066. f.close()
  3067. try:
  3068. fp = open(self.data_path + '/recent_projects.json', 'w')
  3069. except IOError:
  3070. App.log.error("Failed to open recent items file for writing.")
  3071. self.inform.emit('[ERROR_NOTCL] %s' %
  3072. _('Failed to open recent projects file for writing.'))
  3073. return
  3074. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3075. fp.close()
  3076. # Re-build the recent items menu
  3077. self.setup_recent_items()
  3078. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3079. """
  3080. Creates a new specialized FlatCAMObj and attaches it to the application,
  3081. this is, updates the GUI accordingly, any other records and plots it.
  3082. This method is thread-safe.
  3083. Notes:
  3084. * If the name is in use, the self.collection will modify it
  3085. when appending it to the collection. There is no need to handle
  3086. name conflicts here.
  3087. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3088. :type kind: str
  3089. :param name: Name for the object.
  3090. :type name: str
  3091. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3092. The function is called with 2 parameters: the new object and the App instance.
  3093. :type initialize: function
  3094. :param active:
  3095. :param fit:
  3096. :param plot: If to plot the resulting object
  3097. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3098. self.colleaction
  3099. :return: None
  3100. :rtype: None
  3101. """
  3102. App.log.debug("new_object()")
  3103. obj_plot = plot
  3104. obj_autoselected = autoselected
  3105. t0 = time.time() # Debug
  3106. # ## Create object
  3107. classdict = {
  3108. "gerber": FlatCAMGerber,
  3109. "excellon": FlatCAMExcellon,
  3110. "cncjob": FlatCAMCNCjob,
  3111. "geometry": FlatCAMGeometry
  3112. }
  3113. App.log.debug("Calling object constructor...")
  3114. obj = classdict[kind](name)
  3115. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3116. # Set options from "Project options" form
  3117. self.options_read_form()
  3118. # IMPORTANT
  3119. # The key names in defaults and options dictionary's are not random:
  3120. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3121. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  3122. # the options from project options form into the self.options. After that, below, depending on the type of
  3123. # object that is created, it will strip the name of the object and the underline (if the original key was
  3124. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3125. # "toolchange"
  3126. for option in self.options:
  3127. if option.find(kind + "_") == 0:
  3128. oname = option[len(kind) + 1:]
  3129. obj.options[oname] = self.options[option]
  3130. obj.isHovering = False
  3131. obj.notHovering = True
  3132. # Initialize as per user request
  3133. # User must take care to implement initialize
  3134. # in a thread-safe way as is is likely that we
  3135. # have been invoked in a separate thread.
  3136. t1 = time.time()
  3137. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3138. try:
  3139. return_value = initialize(obj, self)
  3140. except Exception as e:
  3141. msg = '[ERROR_NOTCL] %s' % \
  3142. _("An internal error has ocurred. See shell.\n")
  3143. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3144. msg += traceback.format_exc()
  3145. self.inform.emit(msg)
  3146. # if str(e) == "Empty Geometry":
  3147. # self.inform.emit("[ERROR_NOTCL] )
  3148. # else:
  3149. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3150. return "fail"
  3151. t2 = time.time()
  3152. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3153. if return_value == 'fail':
  3154. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3155. return "fail"
  3156. # Check units and convert if necessary
  3157. # This condition CAN be true because initialize() can change obj.units
  3158. if self.options["units"].upper() != obj.units.upper():
  3159. self.inform.emit('%s: %s' %
  3160. (_("Converting units to "), self.options["units"]))
  3161. obj.convert_units(self.options["units"])
  3162. t3 = time.time()
  3163. self.log.debug("%f seconds converting units." % (t3 - t2))
  3164. # Create the bounding box for the object and then add the results to the obj.options
  3165. try:
  3166. xmin, ymin, xmax, ymax = obj.bounds()
  3167. obj.options['xmin'] = xmin
  3168. obj.options['ymin'] = ymin
  3169. obj.options['xmax'] = xmax
  3170. obj.options['ymax'] = ymax
  3171. except Exception as e:
  3172. log.warning("The object has no bounds properties. %s" % str(e))
  3173. return "fail"
  3174. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3175. # Move the object to the main thread and let the app know that it is available.
  3176. obj.moveToThread(self.main_thread)
  3177. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3178. return obj
  3179. def new_excellon_object(self):
  3180. """
  3181. Creates a new, blank Excellon object.
  3182. :return: None
  3183. """
  3184. self.report_usage("new_excellon_object()")
  3185. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3186. def new_geometry_object(self):
  3187. """
  3188. Creates a new, blank and single-tool Geometry object.
  3189. :return: None
  3190. """
  3191. self.report_usage("new_geometry_object()")
  3192. def initialize(obj, self):
  3193. obj.multitool = False
  3194. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3195. def new_gerber_object(self):
  3196. """
  3197. Creates a new, blank Gerber object.
  3198. :return: None
  3199. """
  3200. self.report_usage("new_gerber_object()")
  3201. def initialize(grb_obj, self):
  3202. grb_obj.multitool = False
  3203. grb_obj.source_file = []
  3204. grb_obj.multigeo = False
  3205. grb_obj.follow = False
  3206. grb_obj.apertures = {}
  3207. grb_obj.solid_geometry = []
  3208. try:
  3209. grb_obj.options['xmin'] = 0
  3210. grb_obj.options['ymin'] = 0
  3211. grb_obj.options['xmax'] = 0
  3212. grb_obj.options['ymax'] = 0
  3213. except KeyError:
  3214. pass
  3215. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3216. def on_object_created(self, obj, plot, autoselect):
  3217. """
  3218. Event callback for object creation.
  3219. It will add the new object to the collection. After that it will plot the object in a threaded way
  3220. :param obj: The newly created FlatCAM object.
  3221. :param plot: if the newly create object t obe plotted
  3222. :param autoselect: if the newly created object to be autoselected after creation
  3223. :return: None
  3224. """
  3225. t0 = time.time() # DEBUG
  3226. self.log.debug("on_object_created()")
  3227. # The Collection might change the name if there is a collision
  3228. self.collection.append(obj)
  3229. # after adding the object to the collection always update the list of objects that are in the collection
  3230. self.all_objects_list = self.collection.get_list()
  3231. # self.inform.emit('[selected] %s created & selected: %s' %
  3232. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3233. if obj.kind == 'gerber':
  3234. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3235. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3236. elif obj.kind == 'excellon':
  3237. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3238. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3239. elif obj.kind == 'cncjob':
  3240. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3241. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3242. elif obj.kind == 'geometry':
  3243. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3244. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3245. # update the SHELL auto-completer model with the name of the new object
  3246. self.myKeywords.append(obj.options['name'])
  3247. self.shell._edit.set_model_data(self.myKeywords)
  3248. self.ui.code_editor.set_model_data(self.myKeywords)
  3249. if autoselect:
  3250. # select the just opened object but deselect the previous ones
  3251. self.collection.set_all_inactive()
  3252. self.collection.set_active(obj.options["name"])
  3253. else:
  3254. self.collection.set_all_inactive()
  3255. # here it is done the object plotting
  3256. def worker_task(t_obj):
  3257. with self.proc_container.new(_("Plotting")):
  3258. if isinstance(t_obj, FlatCAMCNCjob):
  3259. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3260. else:
  3261. t_obj.plot()
  3262. t1 = time.time() # DEBUG
  3263. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3264. self.object_plotted.emit(t_obj)
  3265. # Send to worker
  3266. # self.worker.add_task(worker_task, [self])
  3267. if plot is True:
  3268. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3269. def on_object_changed(self, obj):
  3270. """
  3271. Called whenever the geometry of the object was changed in some way.
  3272. This require the update of it's bounding values so it can be the selected on canvas.
  3273. Update the bounding box data from obj.options
  3274. :param obj: the object that was changed
  3275. :return: None
  3276. """
  3277. xmin, ymin, xmax, ymax = obj.bounds()
  3278. obj.options['xmin'] = xmin
  3279. obj.options['ymin'] = ymin
  3280. obj.options['xmax'] = xmax
  3281. obj.options['ymax'] = ymax
  3282. log.debug("Object changed, updating the bounding box data on self.options")
  3283. # delete the old selection shape
  3284. self.delete_selection_shape()
  3285. self.should_we_save = True
  3286. def on_object_plotted(self, obj):
  3287. """
  3288. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3289. :param obj: object to be fit into view
  3290. :return: None
  3291. """
  3292. self.on_zoom_fit(None)
  3293. def options_read_form(self):
  3294. """
  3295. Same as it's equivalent from the defaults.
  3296. self.options use to store the preferences per project. No longer used.
  3297. :return: None
  3298. """
  3299. for option in self.options_form_fields:
  3300. self.options[option] = self.options_form_fields[option].get_value()
  3301. def options_write_form(self):
  3302. """
  3303. Same as it's equivalent from the defaults.
  3304. self.options use to store the preferences per project. No longer used.
  3305. :return: None
  3306. """
  3307. for option in self.options:
  3308. self.options_write_form_field(option)
  3309. def options_write_form_field(self, field):
  3310. """
  3311. Same as it's equivalent from the defaults.
  3312. self.options use to store the preferences per project. No longer used.
  3313. :return: None
  3314. """
  3315. try:
  3316. self.options_form_fields[field].set_value(self.options[field])
  3317. except KeyError:
  3318. # Changed from error to debug. This allows to have data stored
  3319. # which is not user-editable.
  3320. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3321. pass
  3322. def on_about(self):
  3323. """
  3324. Displays the "about" dialog found in the Menu --> Help.
  3325. :return: None
  3326. """
  3327. self.report_usage("on_about")
  3328. version = self.version
  3329. version_date = self.version_date
  3330. beta = self.beta
  3331. class AboutDialog(QtWidgets.QDialog):
  3332. def __init__(self, parent=None):
  3333. QtWidgets.QDialog.__init__(self, parent)
  3334. # Icon and title
  3335. self.setWindowIcon(parent.app_icon)
  3336. self.setWindowTitle(_("About FlatCAM"))
  3337. self.resize(600, 200)
  3338. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3339. # self.setStyleSheet(
  3340. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3341. # "background-attachment: fixed"
  3342. # )
  3343. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3344. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3345. # palette = QtGui.QPalette()
  3346. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3347. # self.setPalette(palette)
  3348. logo = QtWidgets.QLabel()
  3349. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3350. title = QtWidgets.QLabel(
  3351. "<font size=8><B>FlatCAM</B></font><BR>"
  3352. "{title}<BR>"
  3353. "<BR>"
  3354. "<BR>"
  3355. # "<B>{devel}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3356. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3357. # "<b>{down}</B> area &nbsp;&nbsp;&nbsp;&nbsp;"
  3358. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3359. # "<b> {issue}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3360. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3361. "<B>{issue}</B></a><BR>".format(
  3362. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3363. devel=_("Development"),
  3364. down=_("DOWNLOAD"),
  3365. issue=_("Issue tracker"))
  3366. )
  3367. title.setOpenExternalLinks(True)
  3368. closebtn = QtWidgets.QPushButton(_("Close"))
  3369. tab_widget = QtWidgets.QTabWidget()
  3370. description_label = QtWidgets.QLabel(
  3371. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3372. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3373. version=version,
  3374. beta=('BETA' if beta else ''),
  3375. date=version_date,
  3376. arch=platform.architecture()[0])
  3377. )
  3378. description_label.setOpenExternalLinks(True)
  3379. license_label = QtWidgets.QLabel(
  3380. _(
  3381. '(c) Copyright 2014 Juan Pablo Caram.\n\n'
  3382. 'Licensed under the MIT license:\n'
  3383. 'http://www.opensource.org/licenses/mit-license.php\n\n'
  3384. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3385. 'of this software and associated documentation files (the "Software"), to deal\n'
  3386. 'in the Software without restriction, including without limitation the rights\n'
  3387. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3388. 'copies of the Software, and to permit persons to whom the Software is\n'
  3389. ' furnished to do so, subject to the following conditions:\n\n'
  3390. 'The above copyright notice and this permission notice shall be included in\n'
  3391. 'all copies or substantial portions of the Software.\n\n'
  3392. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3393. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3394. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3395. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3396. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3397. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3398. 'THE SOFTWARE.'
  3399. )
  3400. )
  3401. license_label.setOpenExternalLinks(True)
  3402. # layouts
  3403. layout1 = QtWidgets.QVBoxLayout()
  3404. layout1_1 = QtWidgets.QHBoxLayout()
  3405. layout1_2 = QtWidgets.QHBoxLayout()
  3406. layout2 = QtWidgets.QHBoxLayout()
  3407. layout3 = QtWidgets.QHBoxLayout()
  3408. self.setLayout(layout1)
  3409. layout1.addLayout(layout1_1)
  3410. layout1.addLayout(layout1_2)
  3411. layout1.addLayout(layout2)
  3412. layout1.addLayout(layout3)
  3413. layout1_1.addStretch()
  3414. layout1_1.addWidget(description_label)
  3415. layout1_2.addWidget(tab_widget)
  3416. self.splash_tab = QtWidgets.QWidget()
  3417. self.splash_tab.setObjectName("splash_about")
  3418. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3419. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3420. tab_widget.addTab(self.splash_tab, _("Splash"))
  3421. self.programmmers_tab = QtWidgets.QWidget()
  3422. self.programmmers_tab.setObjectName("programmers_about")
  3423. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3424. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3425. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3426. self.translators_tab = QtWidgets.QWidget()
  3427. self.translators_tab.setObjectName("translators_about")
  3428. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3429. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3430. tab_widget.addTab(self.translators_tab, _("Translators"))
  3431. self.license_tab = QtWidgets.QWidget()
  3432. self.license_tab.setObjectName("license_about")
  3433. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3434. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3435. tab_widget.addTab(self.license_tab, _("License"))
  3436. self.splash_tab_layout.addWidget(logo, stretch=0)
  3437. self.splash_tab_layout.addWidget(title, stretch=1)
  3438. pal = QtGui.QPalette()
  3439. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3440. self.prog_form_lay = QtWidgets.QFormLayout()
  3441. self.prog_form_lay.setHorizontalSpacing(20)
  3442. prog_widget = QtWidgets.QWidget()
  3443. prog_widget.setLayout(self.prog_form_lay)
  3444. prog_scroll = QtWidgets.QScrollArea()
  3445. prog_scroll.setWidget(prog_widget)
  3446. prog_scroll.setWidgetResizable(True)
  3447. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3448. prog_scroll.setPalette(pal)
  3449. self.programmmers_tab_layout.addWidget(prog_scroll)
  3450. self.prog_form_lay.addRow(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")),
  3451. QtWidgets.QLabel('<b>%s</b>' % _("Status")))
  3452. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Juan Pablo Caram"),
  3453. QtWidgets.QLabel('%s' % _("Program Author")))
  3454. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Denis Hayrullin"))
  3455. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Kamil Sopko"))
  3456. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marius Stanciu"),
  3457. QtWidgets.QLabel('%s' % _("Maintainer >=2019")))
  3458. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3459. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Alexandru Lazar"))
  3460. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Matthieu Berthomé"))
  3461. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Evans"))
  3462. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Victor Benso"))
  3463. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3464. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Barnaby Walters"))
  3465. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"))
  3466. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lei Zheng"))
  3467. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marco A Quezada"))
  3468. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3469. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Cedric Dussud"))
  3470. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Chris Hemingway"))
  3471. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Damian Wrobel"))
  3472. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Daniel Sallin"))
  3473. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3474. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Bruno Vunderl"))
  3475. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Gonzalo Lopez"))
  3476. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jakob Staudt"))
  3477. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Smith"))
  3478. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3479. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lubos Medovarsky"))
  3480. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Steve Martina"))
  3481. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Thomas Duffin"))
  3482. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3483. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Idechix"))
  3484. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@SM"))
  3485. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@grbf"))
  3486. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Symonty"))
  3487. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@mgix"))
  3488. self.translator_grid_lay = QtWidgets.QGridLayout()
  3489. # trans_widget = QtWidgets.QWidget()
  3490. # trans_widget.setLayout(self.translator_grid_lay)
  3491. # self.translators_tab_layout.addWidget(trans_widget)
  3492. # self.translators_tab_layout.addStretch()
  3493. trans_widget = QtWidgets.QWidget()
  3494. trans_widget.setLayout(self.translator_grid_lay)
  3495. trans_scroll = QtWidgets.QScrollArea()
  3496. trans_scroll.setWidget(trans_widget)
  3497. trans_scroll.setWidgetResizable(True)
  3498. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3499. trans_scroll.setPalette(pal)
  3500. self.translators_tab_layout.addWidget(trans_scroll)
  3501. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3502. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3503. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3504. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Brasilian - Portuguese"), 1, 0)
  3505. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3506. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 1, 2)
  3507. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 2, 0)
  3508. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 2, 1)
  3509. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 2)
  3510. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 3, 0)
  3511. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 3, 1)
  3512. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  3513. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 4, 0)
  3514. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 4, 1)
  3515. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 4, 2)
  3516. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 5, 0)
  3517. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 5, 1)
  3518. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 2)
  3519. self.translator_grid_lay.setColumnStretch(0, 0)
  3520. self.translators_tab_layout.addStretch()
  3521. self.license_tab_layout.addWidget(license_label)
  3522. self.license_tab_layout.addStretch()
  3523. layout3.addStretch()
  3524. layout3.addWidget(closebtn)
  3525. closebtn.clicked.connect(self.accept)
  3526. AboutDialog(self.ui).exec_()
  3527. def on_file_savedefaults(self):
  3528. """
  3529. Callback for menu item File->Save Defaults. Saves application default options
  3530. ``self.defaults`` to current_defaults.FlatConfig.
  3531. :return: None
  3532. """
  3533. self.save_defaults()
  3534. # def on_app_exit(self):
  3535. # self.report_usage("on_app_exit()")
  3536. #
  3537. # if self.collection.get_list():
  3538. # msgbox = QtWidgets.QMessageBox()
  3539. # # msgbox.setText("<B>Save changes ...</B>")
  3540. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3541. # "\n"
  3542. # "Do you want to Save the project?")
  3543. # msgbox.setWindowTitle("Save changes")
  3544. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3545. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3546. # QtWidgets.QMessageBox.Cancel)
  3547. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3548. #
  3549. # response = msgbox.exec_()
  3550. #
  3551. # if response == QtWidgets.QMessageBox.Yes:
  3552. # self.on_file_saveprojectas(thread=False)
  3553. # elif response == QtWidgets.QMessageBox.Cancel:
  3554. # return
  3555. # self.save_defaults()
  3556. # else:
  3557. # self.save_defaults()
  3558. # log.debug("Application defaults saved ... Exit event.")
  3559. # QtWidgets.qApp.quit()
  3560. def save_defaults(self, silent=False, data_path=None):
  3561. """
  3562. Saves application default options
  3563. ``self.defaults`` to current_defaults.FlatConfig file.
  3564. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3565. used at the next launch of the application.
  3566. :param silent: whether to display a message in status bar or not; boolean
  3567. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3568. When the application is portable it should be a mobile location.
  3569. :return: None
  3570. """
  3571. self.report_usage("save_defaults")
  3572. if data_path is None:
  3573. data_path = self.data_path
  3574. # Read options from file
  3575. try:
  3576. f = open(data_path + "/current_defaults.FlatConfig")
  3577. defaults_file_content = f.read()
  3578. f.close()
  3579. except:
  3580. e = sys.exc_info()[0]
  3581. App.log.error("Could not load defaults file.")
  3582. App.log.error(str(e))
  3583. self.inform.emit('[ERROR_NOTCL] %s' %
  3584. _("Could not load defaults file."))
  3585. return
  3586. try:
  3587. defaults = json.loads(defaults_file_content)
  3588. except:
  3589. e = sys.exc_info()[0]
  3590. App.log.error("Failed to parse defaults file.")
  3591. App.log.error(str(e))
  3592. self.inform.emit('[ERROR_NOTCL] %s' %
  3593. _("Failed to parse defaults file."))
  3594. return
  3595. # Update options
  3596. self.defaults_read_form()
  3597. defaults.update(self.defaults)
  3598. self.propagate_defaults(silent=True)
  3599. # Save the toolbar view
  3600. tb_status = 0
  3601. if self.ui.toolbarfile.isVisible():
  3602. tb_status += 1
  3603. if self.ui.toolbargeo.isVisible():
  3604. tb_status += 2
  3605. if self.ui.toolbarview.isVisible():
  3606. tb_status += 4
  3607. if self.ui.toolbartools.isVisible():
  3608. tb_status += 8
  3609. if self.ui.exc_edit_toolbar.isVisible():
  3610. tb_status += 16
  3611. if self.ui.geo_edit_toolbar.isVisible():
  3612. tb_status += 32
  3613. if self.ui.grb_edit_toolbar.isVisible():
  3614. tb_status += 64
  3615. if self.ui.snap_toolbar.isVisible():
  3616. tb_status += 128
  3617. if self.ui.toolbarshell.isVisible():
  3618. tb_status += 256
  3619. self.defaults["global_toolbar_view"] = tb_status
  3620. # Save update options
  3621. try:
  3622. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3623. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3624. f.close()
  3625. except:
  3626. self.inform.emit('[ERROR_NOTCL] %s' %
  3627. _("Failed to write defaults to file."))
  3628. return
  3629. if not silent:
  3630. self.inform.emit('[success] %s' %
  3631. _("Preferences saved."))
  3632. def save_factory_defaults(self, silent=False, data_path=None):
  3633. """
  3634. Saves application factory default options
  3635. ``self.defaults`` to factory_defaults.FlatConfig.
  3636. It's a one time job done just after the first install.
  3637. :param silent: whether to display a message in status bar or not; boolean
  3638. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3639. When the application is portable it should be a mobile location.
  3640. :return: None
  3641. """
  3642. self.report_usage("save_factory_defaults")
  3643. if data_path is None:
  3644. data_path = self.data_path
  3645. # Read options from file
  3646. try:
  3647. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3648. factory_defaults_file_content = f_f_def.read()
  3649. f_f_def.close()
  3650. except:
  3651. e = sys.exc_info()[0]
  3652. App.log.error("Could not load factory defaults file.")
  3653. App.log.error(str(e))
  3654. self.inform.emit('[ERROR_NOTCL] %s' %
  3655. _("Could not load factory defaults file."))
  3656. return
  3657. try:
  3658. factory_defaults = json.loads(factory_defaults_file_content)
  3659. except:
  3660. e = sys.exc_info()[0]
  3661. App.log.error("Failed to parse factory defaults file.")
  3662. App.log.error(str(e))
  3663. self.inform.emit('[ERROR_NOTCL] %s' %
  3664. _("Failed to parse factory defaults file."))
  3665. return
  3666. # Update options
  3667. self.defaults_read_form()
  3668. factory_defaults.update(self.defaults)
  3669. self.propagate_defaults(silent=True)
  3670. # Save update options
  3671. try:
  3672. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  3673. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3674. f_f_def_s.close()
  3675. except:
  3676. self.inform.emit('[ERROR_NOTCL] %s' %
  3677. _("Failed to write factory defaults to file."))
  3678. return
  3679. if silent is False:
  3680. self.inform.emit(_("Factory defaults saved."))
  3681. def final_save(self):
  3682. """
  3683. Callback for doing a preferences save to file whenever the application is about to quit.
  3684. If the project has changes, it will ask the user to save the project.
  3685. :return: None
  3686. """
  3687. if self.save_in_progress:
  3688. self.inform.emit('[WARNING_NOTCL] %s' %
  3689. _("Application is saving the project. Please wait ..."))
  3690. return
  3691. if self.should_we_save and self.collection.get_list():
  3692. msgbox = QtWidgets.QMessageBox()
  3693. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3694. "\n"
  3695. "Do you want to Save the project?"))
  3696. msgbox.setWindowTitle(_("Save changes"))
  3697. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3698. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3699. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3700. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3701. msgbox.setDefaultButton(bt_yes)
  3702. msgbox.exec_()
  3703. response = msgbox.clickedButton()
  3704. if response == bt_yes:
  3705. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  3706. elif response == bt_no:
  3707. self.quit_application()
  3708. elif response == bt_cancel:
  3709. return
  3710. else:
  3711. self.quit_application()
  3712. def quit_application(self):
  3713. """
  3714. Called (as a pyslot or not) when the application is quit.
  3715. :return: None
  3716. """
  3717. self.save_defaults()
  3718. log.debug("App.final_save() --> App Defaults saved.")
  3719. # save toolbar state to file
  3720. settings = QSettings("Open Source", "FlatCAM")
  3721. settings.setValue('saved_gui_state', self.ui.saveState())
  3722. settings.setValue('maximized_gui', self.ui.isMaximized())
  3723. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  3724. settings.setValue('notebook_font_size',
  3725. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value())
  3726. settings.setValue('axis_font_size',
  3727. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  3728. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  3729. # This will write the setting to the platform specific storage.
  3730. del settings
  3731. log.debug("App.final_save() --> App UI state saved.")
  3732. QtWidgets.qApp.quit()
  3733. def on_portable_checked(self, state):
  3734. """
  3735. Callback called when the checkbox in Preferences GUI is checked.
  3736. It will set the application as portable by creating the preferences and recent files in the
  3737. 'config' folder found in the FlatCAM installation folder.
  3738. :param state: boolean, the state of the checkbox when clicked/checked
  3739. :return:
  3740. """
  3741. line_no = 0
  3742. data = None
  3743. if sys.platform != 'win32':
  3744. # this won't work in Linux or MacOS
  3745. return
  3746. # test if the app was frozen and choose the path for the configuration file
  3747. if getattr(sys, "frozen", False) is True:
  3748. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3749. else:
  3750. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3751. config_file = current_data_path + '\\configuration.txt'
  3752. try:
  3753. with open(config_file, 'r') as f:
  3754. try:
  3755. data = f.readlines()
  3756. except Exception as e:
  3757. log.debug('App.__init__() -->%s' % str(e))
  3758. return
  3759. except FileNotFoundError:
  3760. pass
  3761. for line in data:
  3762. line = line.strip('\n')
  3763. param = str(line).rpartition('=')
  3764. if param[0] == 'portable':
  3765. break
  3766. line_no += 1
  3767. if state:
  3768. data[line_no] = 'portable=True\n'
  3769. # create the new defauults files
  3770. # create current_defaults.FlatConfig file if there is none
  3771. try:
  3772. f = open(current_data_path + '/current_defaults.FlatConfig')
  3773. f.close()
  3774. except IOError:
  3775. App.log.debug('Creating empty current_defaults.FlatConfig')
  3776. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3777. json.dump({}, f)
  3778. f.close()
  3779. # create factory_defaults.FlatConfig file if there is none
  3780. try:
  3781. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3782. f.close()
  3783. except IOError:
  3784. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3785. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3786. json.dump({}, f)
  3787. f.close()
  3788. try:
  3789. f = open(current_data_path + '/recent.json')
  3790. f.close()
  3791. except IOError:
  3792. App.log.debug('Creating empty recent.json')
  3793. f = open(current_data_path + '/recent.json', 'w')
  3794. json.dump([], f)
  3795. f.close()
  3796. try:
  3797. fp = open(current_data_path + '/recent_projects.json')
  3798. fp.close()
  3799. except IOError:
  3800. App.log.debug('Creating empty recent_projects.json')
  3801. fp = open(current_data_path + '/recent_projects.json', 'w')
  3802. json.dump([], fp)
  3803. fp.close()
  3804. # save the current defaults to the new defaults file
  3805. self.save_defaults(silent=True, data_path=current_data_path)
  3806. self.save_factory_defaults(silent=True, data_path=current_data_path)
  3807. else:
  3808. data[line_no] = 'portable=False\n'
  3809. with open(config_file, 'w') as f:
  3810. f.writelines(data)
  3811. def on_toggle_shell(self):
  3812. """
  3813. Toggle shell: if is visible close it, if it is closed then open it
  3814. :return:
  3815. """
  3816. self.report_usage("on_toggle_shell()")
  3817. if self.ui.shell_dock.isVisible():
  3818. self.ui.shell_dock.hide()
  3819. else:
  3820. self.ui.shell_dock.show()
  3821. def on_register_files(self, obj_type=None):
  3822. """
  3823. Called whenever there is a need to register file extensions with FlatCAM.
  3824. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3825. :param obj_type: the type of object to be register for.
  3826. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3827. :return: None
  3828. """
  3829. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3830. new_reg_path = 'Software\\Classes\\'
  3831. # find if the current user is admin
  3832. try:
  3833. is_admin = os.getuid() == 0
  3834. except AttributeError:
  3835. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3836. if is_admin is True:
  3837. root_path = winreg.HKEY_CLASSES_ROOT
  3838. else:
  3839. root_path = winreg.HKEY_CURRENT_USER
  3840. # create the keys
  3841. def set_reg(name, root_path, new_reg_path, value):
  3842. try:
  3843. winreg.CreateKey(root_path, new_reg_path)
  3844. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3845. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3846. return True
  3847. except WindowsError:
  3848. return False
  3849. # delete key in registry
  3850. def delete_reg(root_path, reg_path, key_to_del):
  3851. key_to_del_path = reg_path + key_to_del
  3852. try:
  3853. winreg.DeleteKey(root_path, key_to_del_path)
  3854. return True
  3855. except WindowsError:
  3856. return False
  3857. if obj_type is None or obj_type == 'excellon':
  3858. exc_list = self.ui.fa_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3859. exc_list = [x for x in exc_list if x != '']
  3860. # register all keys in the Preferences window
  3861. for ext in exc_list:
  3862. new_k = new_reg_path + ext
  3863. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3864. # and unregister those that are no longer in the Preferences windows but are in the file
  3865. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3866. if ext not in exc_list:
  3867. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3868. # now write the updated extensions to the self.defaults
  3869. new_ext = ''
  3870. for ext in exc_list:
  3871. new_ext = new_ext + ext + ', '
  3872. self.defaults["fa_excellon"] = new_ext
  3873. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3874. if obj_type is None or obj_type == 'gcode':
  3875. gco_list = self.ui.fa_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3876. gco_list = [x for x in gco_list if x != '']
  3877. # register all keys in the Preferences window
  3878. for ext in gco_list:
  3879. new_k = new_reg_path + ext
  3880. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3881. # and unregister those that are no longer in the Preferences windows but are in the file
  3882. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3883. if ext not in gco_list:
  3884. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3885. # now write the updated extensions to the self.defaults
  3886. new_ext = ''
  3887. for ext in gco_list:
  3888. new_ext = new_ext + ext + ', '
  3889. self.defaults["fa_gcode"] = new_ext
  3890. self.inform.emit('[success] %s' %
  3891. _("Selected GCode file extensions registered with FlatCAM."))
  3892. if obj_type is None or obj_type == 'gerber':
  3893. grb_list = self.ui.fa_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3894. grb_list = [x for x in grb_list if x != '']
  3895. # register all keys in the Preferences window
  3896. for ext in grb_list:
  3897. new_k = new_reg_path + ext
  3898. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3899. # and unregister those that are no longer in the Preferences windows but are in the file
  3900. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3901. if ext not in grb_list:
  3902. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3903. # now write the updated extensions to the self.defaults
  3904. new_ext = ''
  3905. for ext in grb_list:
  3906. new_ext = new_ext + ext + ', '
  3907. self.defaults["fa_gerber"] = new_ext
  3908. self.inform.emit('[success] %s' %
  3909. _("Selected Gerber file extensions registered with FlatCAM."))
  3910. def on_edit_join(self, name=None):
  3911. """
  3912. Callback for Edit->Join. Joins the selected geometry objects into
  3913. a new one.
  3914. :return: None
  3915. """
  3916. self.report_usage("on_edit_join()")
  3917. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3918. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3919. tooldias = []
  3920. geo_type_list = set()
  3921. objs = self.collection.get_selected()
  3922. if len(objs) < 2:
  3923. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3924. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3925. return 'fail'
  3926. for obj in objs:
  3927. geo_type_list.add(obj.multigeo)
  3928. # if len(geo_type_list) == 1 means that all list elements are the same
  3929. if len(geo_type_list) != 1:
  3930. self.inform.emit('[ERROR] %s' %
  3931. _("Failed join. The Geometry objects are of different types.\n"
  3932. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3933. "convert from one to another and retry joining \n"
  3934. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3935. "the result may not be what was expected. \n"
  3936. "Check the generated GCODE."))
  3937. return
  3938. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3939. if True in geo_type_list:
  3940. def initialize(obj, app):
  3941. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  3942. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3943. for v in obj.tools.values():
  3944. v['data']['name'] = obj_name_multi
  3945. self.new_object("geometry", obj_name_multi, initialize)
  3946. else:
  3947. def initialize(obj, app):
  3948. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  3949. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3950. for v in obj.tools.values():
  3951. v['data']['name'] = obj_name_single
  3952. self.new_object("geometry", obj_name_single, initialize)
  3953. self.should_we_save = True
  3954. def on_edit_join_exc(self):
  3955. """
  3956. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3957. a new Excellon.
  3958. :return: None
  3959. """
  3960. self.report_usage("on_edit_join_exc()")
  3961. objs = self.collection.get_selected()
  3962. for obj in objs:
  3963. if not isinstance(obj, FlatCAMExcellon):
  3964. self.inform.emit('[ERROR_NOTCL] %s' %
  3965. _("Failed. Excellon joining works only on Excellon objects."))
  3966. return
  3967. if len(objs) < 2:
  3968. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3969. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3970. return 'fail'
  3971. def initialize(obj, app):
  3972. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  3973. self.new_object("excellon", 'Combo_Excellon', initialize)
  3974. self.should_we_save = True
  3975. def on_edit_join_grb(self):
  3976. """
  3977. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3978. a new Gerber object.
  3979. :return: None
  3980. """
  3981. self.report_usage("on_edit_join_grb()")
  3982. objs = self.collection.get_selected()
  3983. for obj in objs:
  3984. if not isinstance(obj, FlatCAMGerber):
  3985. self.inform.emit('[ERROR_NOTCL] %s' %
  3986. _("Failed. Gerber joining works only on Gerber objects."))
  3987. return
  3988. if len(objs) < 2:
  3989. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3990. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3991. return 'fail'
  3992. def initialize(obj, app):
  3993. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  3994. self.new_object("gerber", 'Combo_Gerber', initialize)
  3995. self.should_we_save = True
  3996. def on_convert_singlegeo_to_multigeo(self):
  3997. """
  3998. Called for converting a Geometry object from single-geo to multi-geo.
  3999. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4000. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4001. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4002. the solid-geometry of that tool.
  4003. :return: None
  4004. """
  4005. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4006. obj = self.collection.get_active()
  4007. if obj is None:
  4008. self.inform.emit('[ERROR_NOTCL] %s' %
  4009. _("Failed. Select a Geometry Object and try again."))
  4010. return
  4011. if not isinstance(obj, FlatCAMGeometry):
  4012. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4013. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4014. return
  4015. obj.multigeo = True
  4016. for tooluid, dict_value in obj.tools.items():
  4017. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4018. if not isinstance(obj.solid_geometry, list):
  4019. obj.solid_geometry = [obj.solid_geometry]
  4020. obj.solid_geometry[:] = []
  4021. obj.plot()
  4022. self.should_we_save = True
  4023. self.inform.emit('[success] %s' %
  4024. _("A Geometry object was converted to MultiGeo type."))
  4025. def on_convert_multigeo_to_singlegeo(self):
  4026. """
  4027. Called for converting a Geometry object from multi-geo to single-geo.
  4028. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4029. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4030. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4031. the solid-geometry of that tool.
  4032. :return: None
  4033. """
  4034. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4035. obj = self.collection.get_active()
  4036. if obj is None:
  4037. self.inform.emit('[ERROR_NOTCL] %s' %
  4038. _("Failed. Select a Geometry Object and try again."))
  4039. return
  4040. if not isinstance(obj, FlatCAMGeometry):
  4041. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4042. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4043. return
  4044. obj.multigeo = False
  4045. total_solid_geometry = []
  4046. for tooluid, dict_value in obj.tools.items():
  4047. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4048. # clear the original geometry
  4049. dict_value['solid_geometry'][:] = []
  4050. obj.solid_geometry = deepcopy(total_solid_geometry)
  4051. obj.plot()
  4052. self.should_we_save = True
  4053. self.inform.emit('[success] %s' %
  4054. _("A Geometry object was converted to SingleGeo type."))
  4055. def on_options_dict_change(self, field):
  4056. """
  4057. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  4058. current project. This feature is no longer used.
  4059. :param field:
  4060. :return:
  4061. """
  4062. self.options_write_form_field(field)
  4063. if field == "units":
  4064. self.set_screen_units(self.options['units'])
  4065. def on_defaults_dict_change(self, field):
  4066. """
  4067. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4068. Edit -> Preferences tab window.
  4069. :param field: the key of the self.defaults dictionary that was changed.
  4070. :return: None
  4071. """
  4072. self.defaults_write_form_field(field)
  4073. if field == "units":
  4074. self.set_screen_units(self.defaults['units'])
  4075. def set_screen_units(self, units):
  4076. """
  4077. Set the FlatCAM units on the status bar.
  4078. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4079. :return: None
  4080. """
  4081. self.ui.units_label.setText("[" + units.lower() + "]")
  4082. def on_toggle_units(self, no_pref=False):
  4083. """
  4084. Callback for the Units radio-button change in the Preferences tab.
  4085. Changes the application's default units adn for the project too.
  4086. If changing the project's units, the change propagates to all of
  4087. the objects in the project.
  4088. :return: None
  4089. """
  4090. self.report_usage("on_toggle_units")
  4091. if self.toggle_units_ignore:
  4092. return
  4093. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4094. # If option is the same, then ignore
  4095. if new_units == self.defaults["units"].upper():
  4096. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4097. return
  4098. # Options to scale
  4099. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  4100. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4101. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4102. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4103. "excellon_z_pdepth",
  4104. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4105. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4106. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4107. "geometry_feedrate_probe",
  4108. 'cncjob_tooldia',
  4109. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4110. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia"
  4111. "tools_2sided_drilldia", "tools_film_boundary",
  4112. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4113. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4114. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4115. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4116. "tools_transform_offset_y",
  4117. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4118. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4119. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4120. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4121. 'global_gridx', 'global_gridy', 'global_snap_max']
  4122. def scale_options(sfactor):
  4123. for dim in dimensions:
  4124. if dim == 'excellon_toolchangexy':
  4125. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4126. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4127. coords_xy[0] *= sfactor
  4128. coords_xy[1] *= sfactor
  4129. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4130. elif dim == 'geometry_toolchangexy':
  4131. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4132. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4133. coords_xy[0] *= sfactor
  4134. coords_xy[1] *= sfactor
  4135. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4136. elif dim == 'geometry_cnctooldia':
  4137. tools_diameters = []
  4138. try:
  4139. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4140. tools_diameters = [eval(a) for a in tools_string if a != '']
  4141. except Exception as e:
  4142. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4143. self.options['geometry_cnctooldia'] = ''
  4144. for t in range(len(tools_diameters)):
  4145. tools_diameters[t] *= sfactor
  4146. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  4147. elif dim == 'tools_ncctools':
  4148. ncctools = []
  4149. try:
  4150. tools_string = self.defaults["tools_ncctools"].split(",")
  4151. ncctools = [eval(a) for a in tools_string if a != '']
  4152. except Exception as e:
  4153. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4154. self.options['tools_ncctools'] = ''
  4155. for t in range(len(ncctools)):
  4156. ncctools[t] *= sfactor
  4157. self.options['tools_ncctools'] += "%f," % ncctools[t]
  4158. elif dim == 'tools_solderpaste_tools':
  4159. sptools = []
  4160. try:
  4161. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4162. sptools = [eval(a) for a in tools_string if a != '']
  4163. except Exception as e:
  4164. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4165. self.options['tools_solderpaste_tools'] = ""
  4166. for t in range(len(sptools)):
  4167. sptools[t] *= sfactor
  4168. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  4169. elif dim == 'tools_solderpaste_xy_toolchange':
  4170. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4171. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4172. sp_coords[0] *= sfactor
  4173. sp_coords[1] *= sfactor
  4174. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  4175. elif dim == 'global_gridx' or dim == 'global_gridy':
  4176. if new_units == 'IN':
  4177. val = 0.1
  4178. try:
  4179. val = float(self.defaults[dim]) * sfactor
  4180. except Exception as e:
  4181. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4182. self.options[dim] = float('%.6f' % val)
  4183. else:
  4184. val = 0.1
  4185. try:
  4186. val = float(self.defaults[dim]) * sfactor
  4187. except Exception as e:
  4188. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4189. self.options[dim] = float('%.4f' % val)
  4190. else:
  4191. val = 0.1
  4192. try:
  4193. val = float(self.options[dim]) * sfactor
  4194. except Exception as e:
  4195. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  4196. self.options[dim] = val
  4197. def scale_defaults(sfactor):
  4198. for dim in dimensions:
  4199. if dim == 'excellon_toolchangexy':
  4200. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4201. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4202. coords_xy[0] *= sfactor
  4203. coords_xy[1] *= sfactor
  4204. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4205. elif dim == 'geometry_toolchangexy':
  4206. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4207. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4208. coords_xy[0] *= sfactor
  4209. coords_xy[1] *= sfactor
  4210. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4211. elif dim == 'geometry_cnctooldia':
  4212. tools_diameters = []
  4213. try:
  4214. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4215. tools_diameters = [eval(a) for a in tools_string if a != '']
  4216. except Exception as e:
  4217. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4218. self.defaults['geometry_cnctooldia'] = ''
  4219. for t in range(len(tools_diameters)):
  4220. tools_diameters[t] *= sfactor
  4221. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  4222. elif dim == 'tools_ncctools':
  4223. ncctools = []
  4224. try:
  4225. tools_string = self.defaults["tools_ncctools"].split(",")
  4226. ncctools = [eval(a) for a in tools_string if a != '']
  4227. except Exception as e:
  4228. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4229. self.defaults['tools_ncctools'] = ''
  4230. for t in range(len(ncctools)):
  4231. ncctools[t] *= sfactor
  4232. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  4233. elif dim == 'tools_solderpaste_tools':
  4234. sptools = []
  4235. try:
  4236. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4237. sptools = [eval(a) for a in tools_string if a != '']
  4238. except Exception as e:
  4239. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4240. self.defaults['tools_solderpaste_tools'] = ""
  4241. for t in range(len(sptools)):
  4242. sptools[t] *= sfactor
  4243. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4244. elif dim == 'tools_solderpaste_xy_toolchange':
  4245. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4246. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4247. sp_coords[0] *= sfactor
  4248. sp_coords[1] *= sfactor
  4249. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  4250. elif dim == 'global_gridx' or dim == 'global_gridy':
  4251. if new_units == 'IN':
  4252. val = 0.1
  4253. try:
  4254. val = float(self.defaults[dim]) * sfactor
  4255. except Exception as e:
  4256. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4257. self.defaults[dim] = float('%.6f' % val)
  4258. else:
  4259. val = 0.1
  4260. try:
  4261. val = float(self.defaults[dim]) * sfactor
  4262. except Exception as e:
  4263. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4264. self.defaults[dim] = float('%.4f' % val)
  4265. else:
  4266. val = 0.1
  4267. try:
  4268. val = float(self.defaults[dim]) * sfactor
  4269. except Exception as e:
  4270. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4271. self.defaults[dim] = val
  4272. # The scaling factor depending on choice of units.
  4273. factor = 1/25.4
  4274. if new_units == 'MM':
  4275. factor = 25.4
  4276. # Changing project units. Warn user.
  4277. msgbox = QtWidgets.QMessageBox()
  4278. msgbox.setWindowTitle(_("Toggle Units"))
  4279. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4280. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4281. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4282. "properties of all objects to be scaled accordingly.\nContinue?"))
  4283. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4284. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4285. msgbox.setDefaultButton(bt_ok)
  4286. msgbox.exec_()
  4287. response = msgbox.clickedButton()
  4288. if response == bt_ok:
  4289. if no_pref is False:
  4290. self.options_read_form()
  4291. scale_options(factor)
  4292. self.options_write_form()
  4293. self.defaults_read_form()
  4294. scale_defaults(factor)
  4295. self.defaults_write_form(fl_units=new_units)
  4296. # save the defaults to file, some may assume that the conversion is enough and it's not
  4297. self.on_save_button()
  4298. self.should_we_save = True
  4299. # change this only if the workspace is active
  4300. if self.defaults['global_workspace'] is True:
  4301. self.plotcanvas.draw_workspace()
  4302. # adjust the grid values on the main toolbar
  4303. dec = 6 if new_units == 'IN'else 4
  4304. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4305. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4306. if not self.ui.grid_gap_link_cb.isChecked():
  4307. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4308. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4309. for obj in self.collection.get_list():
  4310. obj.convert_units(new_units)
  4311. # make that the properties stored in the object are also updated
  4312. self.object_changed.emit(obj)
  4313. obj.build_ui()
  4314. current = self.collection.get_active()
  4315. if current is not None:
  4316. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4317. if not isinstance(current, FlatCAMGeometry):
  4318. current.to_form()
  4319. self.plot_all()
  4320. self.inform.emit('[success] %s: %s' %
  4321. (_("Converted units to"), new_units))
  4322. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4323. self.set_screen_units(new_units)
  4324. else:
  4325. # Undo toggling
  4326. self.toggle_units_ignore = True
  4327. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4328. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4329. else:
  4330. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4331. self.toggle_units_ignore = False
  4332. self.inform.emit('[WARNING_NOTCL]%s' %
  4333. _(" Units conversion cancelled."))
  4334. self.options_read_form()
  4335. self.defaults_read_form()
  4336. def on_toggle_units_click(self):
  4337. try:
  4338. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4339. except (TypeError, AttributeError):
  4340. pass
  4341. if self.defaults["units"] == 'MM':
  4342. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4343. else:
  4344. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4345. self.on_toggle_units(no_pref=True)
  4346. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4347. lambda: self.on_toggle_units(no_pref=False))
  4348. def on_fullscreen(self):
  4349. self.report_usage("on_fullscreen()")
  4350. if self.toggle_fscreen is False:
  4351. if sys.platform == 'win32':
  4352. self.ui.showFullScreen()
  4353. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4354. tb.setVisible(False)
  4355. self.ui.splitter_left.setVisible(False)
  4356. self.toggle_fscreen = True
  4357. else:
  4358. if sys.platform == 'win32':
  4359. self.ui.showNormal()
  4360. self.restore_toolbar_view()
  4361. self.ui.splitter_left.setVisible(True)
  4362. self.toggle_fscreen = False
  4363. def on_toggle_plotarea(self):
  4364. self.report_usage("on_toggle_plotarea()")
  4365. try:
  4366. name = self.ui.plot_tab_area.widget(0).objectName()
  4367. except AttributeError:
  4368. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4369. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4370. self.ui.plot_tab_area.protectTab(0)
  4371. return
  4372. if name != 'plotarea':
  4373. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4374. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4375. self.ui.plot_tab_area.protectTab(0)
  4376. else:
  4377. self.ui.plot_tab_area.closeTab(0)
  4378. def on_toggle_notebook(self):
  4379. if self.ui.splitter.sizes()[0] == 0:
  4380. self.ui.splitter.setSizes([1, 1])
  4381. else:
  4382. self.ui.splitter.setSizes([0, 1])
  4383. def on_toggle_axis(self):
  4384. self.report_usage("on_toggle_axis()")
  4385. if self.toggle_axis is False:
  4386. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4387. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4388. self.plotcanvas.redraw()
  4389. self.toggle_axis = True
  4390. else:
  4391. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4392. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4393. self.plotcanvas.redraw()
  4394. self.toggle_axis = False
  4395. def on_toggle_grid(self):
  4396. self.report_usage("on_toggle_grid()")
  4397. self.ui.grid_snap_btn.trigger()
  4398. def on_options_combo_change(self, sel):
  4399. """
  4400. Called when the combo box to choose between application defaults and
  4401. project option changes value. The corresponding variables are
  4402. copied to the UI.
  4403. :param sel: The option index that was chosen.
  4404. :return: None
  4405. """
  4406. # combo_sel = self.ui.notebook.combo_options.get_active()
  4407. App.log.debug("Options --> %s" % sel)
  4408. # form = [self.defaults_form, self.options_form][sel]
  4409. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  4410. if sel == 0:
  4411. self.gen_form = self.ui.general_defaults_form
  4412. self.ger_form = self.ui.gerber_defaults_form
  4413. self.exc_form = self.ui.excellon_defaults_form
  4414. self.geo_form = self.ui.geometry_defaults_form
  4415. self.cnc_form = self.ui.cncjob_defaults_form
  4416. self.tools_form = self.ui.tools_defaults_form
  4417. self.fa_form = self.ui.fa_defaults_form
  4418. elif sel == 1:
  4419. self.gen_form = self.ui.general_options_form
  4420. self.ger_form = self.ui.gerber_options_form
  4421. self.exc_form = self.ui.excellon_options_form
  4422. self.geo_form = self.ui.geometry_options_form
  4423. self.cnc_form = self.ui.cncjob_options_form
  4424. self.tools_form = self.ui.tools_options_form
  4425. self.fa_form = self.ui.fa_options_form
  4426. else:
  4427. return
  4428. try:
  4429. self.ui.general_scroll_area.takeWidget()
  4430. except:
  4431. self.log.debug("Nothing to remove")
  4432. self.ui.general_scroll_area.setWidget(self.gen_form)
  4433. self.gen_form.show()
  4434. try:
  4435. self.ui.gerber_scroll_area.takeWidget()
  4436. except:
  4437. self.log.debug("Nothing to remove")
  4438. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4439. self.ger_form.show()
  4440. try:
  4441. self.ui.excellon_scroll_area.takeWidget()
  4442. except:
  4443. self.log.debug("Nothing to remove")
  4444. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4445. self.exc_form.show()
  4446. try:
  4447. self.ui.geometry_scroll_area.takeWidget()
  4448. except:
  4449. self.log.debug("Nothing to remove")
  4450. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4451. self.geo_form.show()
  4452. try:
  4453. self.ui.cncjob_scroll_area.takeWidget()
  4454. except:
  4455. self.log.debug("Nothing to remove")
  4456. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4457. self.cnc_form.show()
  4458. try:
  4459. self.ui.tools_scroll_area.takeWidget()
  4460. except:
  4461. self.log.debug("Nothing to remove")
  4462. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4463. self.tools_form.show()
  4464. try:
  4465. self.ui.fa_scroll_area.takeWidget()
  4466. except:
  4467. self.log.debug("Nothing to remove")
  4468. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4469. self.fa_form.show()
  4470. self.log.debug("Finished GUI form initialization.")
  4471. # self.options2form()
  4472. def on_excellon_defaults_button(self):
  4473. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  4474. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  4475. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  4476. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  4477. self.defaults_form_fields["excellon_zeros"].set_value('L')
  4478. self.defaults_form_fields["excellon_units"].set_value('INCH')
  4479. log.debug("Excellon app defaults loaded ...")
  4480. def on_excellon_options_button(self):
  4481. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  4482. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  4483. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  4484. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  4485. self.options_form_fields["excellon_zeros"].set_value('L')
  4486. self.options_form_fields["excellon_units"].set_value('INCH')
  4487. log.debug("Excellon options defaults loaded ...")
  4488. def on_update_exc_export(self, state):
  4489. """
  4490. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  4491. if the update_excellon_cb checkbox is checked
  4492. :param state: state of the checkbox whose signals is tied to his slot
  4493. :return:
  4494. """
  4495. if state:
  4496. # first try to disconnect
  4497. try:
  4498. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.\
  4499. disconnect(self.on_excellon_format_changed)
  4500. except TypeError:
  4501. pass
  4502. try:
  4503. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.\
  4504. disconnect(self.on_excellon_format_changed)
  4505. except TypeError:
  4506. pass
  4507. try:
  4508. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.\
  4509. disconnect(self.on_excellon_format_changed)
  4510. except TypeError:
  4511. pass
  4512. try:
  4513. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.\
  4514. disconnect(self.on_excellon_format_changed)
  4515. except TypeError:
  4516. pass
  4517. try:
  4518. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  4519. disconnect(self.on_excellon_zeros_changed)
  4520. except TypeError:
  4521. pass
  4522. try:
  4523. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  4524. disconnect(self.on_excellon_zeros_changed)
  4525. except TypeError:
  4526. pass
  4527. # the connect them
  4528. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.connect(
  4529. self.on_excellon_format_changed)
  4530. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.connect(
  4531. self.on_excellon_format_changed)
  4532. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.connect(
  4533. self.on_excellon_format_changed)
  4534. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.connect(
  4535. self.on_excellon_format_changed)
  4536. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  4537. self.on_excellon_zeros_changed)
  4538. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  4539. self.on_excellon_units_changed)
  4540. else:
  4541. # disconnect the signals
  4542. try:
  4543. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged. \
  4544. disconnect(self.on_excellon_format_changed)
  4545. except TypeError:
  4546. pass
  4547. try:
  4548. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged. \
  4549. disconnect(self.on_excellon_format_changed)
  4550. except TypeError:
  4551. pass
  4552. try:
  4553. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged. \
  4554. disconnect(self.on_excellon_format_changed)
  4555. except TypeError:
  4556. pass
  4557. try:
  4558. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged. \
  4559. disconnect(self.on_excellon_format_changed)
  4560. except TypeError:
  4561. pass
  4562. try:
  4563. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  4564. disconnect(self.on_excellon_zeros_changed)
  4565. except TypeError:
  4566. pass
  4567. try:
  4568. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  4569. disconnect(self.on_excellon_zeros_changed)
  4570. except TypeError:
  4571. pass
  4572. def on_excellon_format_changed(self):
  4573. """
  4574. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  4575. :return: None
  4576. """
  4577. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  4578. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4579. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  4580. )
  4581. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4582. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  4583. )
  4584. else:
  4585. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4586. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  4587. )
  4588. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4589. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  4590. )
  4591. def on_excellon_zeros_changed(self):
  4592. """
  4593. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  4594. :return: None
  4595. """
  4596. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  4597. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  4598. )
  4599. def on_excellon_units_changed(self):
  4600. """
  4601. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  4602. :return: None
  4603. """
  4604. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  4605. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  4606. )
  4607. self.on_excellon_format_changed()
  4608. # Setting plot colors handlers
  4609. def on_pf_color_entry(self):
  4610. self.defaults['global_plot_fill'] = \
  4611. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  4612. self.defaults['global_plot_fill'][7:9]
  4613. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4614. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  4615. def on_pf_color_button(self):
  4616. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  4617. c_dialog = QtWidgets.QColorDialog()
  4618. plot_fill_color = c_dialog.getColor(initial=current_color)
  4619. if plot_fill_color.isValid() is False:
  4620. return
  4621. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4622. "background-color:%s" % str(plot_fill_color.name()))
  4623. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  4624. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  4625. self.defaults['global_plot_fill'] = new_val
  4626. def on_pf_color_spinner(self):
  4627. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  4628. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  4629. self.defaults['global_plot_fill'] = \
  4630. self.defaults['global_plot_fill'][:7] + \
  4631. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4632. self.defaults['global_plot_line'] = \
  4633. self.defaults['global_plot_line'][:7] + \
  4634. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4635. def on_pf_color_slider(self):
  4636. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  4637. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  4638. def on_pl_color_entry(self):
  4639. self.defaults['global_plot_line'] = \
  4640. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  4641. self.defaults['global_plot_line'][7:9]
  4642. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4643. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  4644. def on_pl_color_button(self):
  4645. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  4646. # print(current_color)
  4647. c_dialog = QtWidgets.QColorDialog()
  4648. plot_line_color = c_dialog.getColor(initial=current_color)
  4649. if plot_line_color.isValid() is False:
  4650. return
  4651. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4652. "background-color:%s" % str(plot_line_color.name()))
  4653. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  4654. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  4655. self.defaults['global_plot_line'] = new_val_line
  4656. # Setting selection colors (left - right) handlers
  4657. def on_sf_color_entry(self):
  4658. self.defaults['global_sel_fill'] = \
  4659. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  4660. self.defaults['global_sel_fill'][7:9]
  4661. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4662. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  4663. def on_sf_color_button(self):
  4664. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  4665. c_dialog = QtWidgets.QColorDialog()
  4666. plot_fill_color = c_dialog.getColor(initial=current_color)
  4667. if plot_fill_color.isValid() is False:
  4668. return
  4669. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4670. "background-color:%s" % str(plot_fill_color.name()))
  4671. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  4672. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  4673. self.defaults['global_sel_fill'] = new_val
  4674. def on_sf_color_spinner(self):
  4675. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  4676. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  4677. self.defaults['global_sel_fill'] = \
  4678. self.defaults['global_sel_fill'][:7] + \
  4679. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4680. self.defaults['global_sel_line'] = \
  4681. self.defaults['global_sel_line'][:7] + \
  4682. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4683. def on_sf_color_slider(self):
  4684. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  4685. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  4686. def on_sl_color_entry(self):
  4687. self.defaults['global_sel_line'] = \
  4688. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  4689. self.defaults['global_sel_line'][7:9]
  4690. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4691. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  4692. def on_sl_color_button(self):
  4693. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  4694. c_dialog = QtWidgets.QColorDialog()
  4695. plot_line_color = c_dialog.getColor(initial=current_color)
  4696. if plot_line_color.isValid() is False:
  4697. return
  4698. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4699. "background-color:%s" % str(plot_line_color.name()))
  4700. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  4701. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  4702. self.defaults['global_sel_line'] = new_val_line
  4703. # Setting selection colors (right - left) handlers
  4704. def on_alt_sf_color_entry(self):
  4705. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  4706. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  4707. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4708. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  4709. def on_alt_sf_color_button(self):
  4710. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  4711. c_dialog = QtWidgets.QColorDialog()
  4712. plot_fill_color = c_dialog.getColor(initial=current_color)
  4713. if plot_fill_color.isValid() is False:
  4714. return
  4715. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4716. "background-color:%s" % str(plot_fill_color.name()))
  4717. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  4718. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  4719. self.defaults['global_alt_sel_fill'] = new_val
  4720. def on_alt_sf_color_spinner(self):
  4721. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  4722. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  4723. self.defaults['global_alt_sel_fill'] = \
  4724. self.defaults['global_alt_sel_fill'][:7] + \
  4725. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4726. self.defaults['global_alt_sel_line'] = \
  4727. self.defaults['global_alt_sel_line'][:7] + \
  4728. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4729. def on_alt_sf_color_slider(self):
  4730. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  4731. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  4732. def on_alt_sl_color_entry(self):
  4733. self.defaults['global_alt_sel_line'] = \
  4734. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  4735. self.defaults['global_alt_sel_line'][7:9]
  4736. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4737. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  4738. def on_alt_sl_color_button(self):
  4739. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  4740. c_dialog = QtWidgets.QColorDialog()
  4741. plot_line_color = c_dialog.getColor(initial=current_color)
  4742. if plot_line_color.isValid() is False:
  4743. return
  4744. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4745. "background-color:%s" % str(plot_line_color.name()))
  4746. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  4747. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  4748. self.defaults['global_alt_sel_line'] = new_val_line
  4749. # Setting Editor colors
  4750. def on_draw_color_entry(self):
  4751. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  4752. .draw_color_entry.get_value()
  4753. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  4754. "background-color:%s" % str(self.defaults['global_draw_color']))
  4755. def on_draw_color_button(self):
  4756. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  4757. c_dialog = QtWidgets.QColorDialog()
  4758. draw_color = c_dialog.getColor(initial=current_color)
  4759. if draw_color.isValid() is False:
  4760. return
  4761. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  4762. "background-color:%s" % str(draw_color.name()))
  4763. new_val = str(draw_color.name())
  4764. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  4765. self.defaults['global_draw_color'] = new_val
  4766. def on_sel_draw_color_entry(self):
  4767. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  4768. .sel_draw_color_entry.get_value()
  4769. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  4770. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  4771. def on_sel_draw_color_button(self):
  4772. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  4773. c_dialog = QtWidgets.QColorDialog()
  4774. sel_draw_color = c_dialog.getColor(initial=current_color)
  4775. if sel_draw_color.isValid() is False:
  4776. return
  4777. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  4778. "background-color:%s" % str(sel_draw_color.name()))
  4779. new_val_sel = str(sel_draw_color.name())
  4780. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  4781. self.defaults['global_sel_draw_color'] = new_val_sel
  4782. def on_proj_color_entry(self):
  4783. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  4784. .proj_color_entry.get_value()
  4785. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  4786. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  4787. def on_proj_color_button(self):
  4788. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  4789. c_dialog = QtWidgets.QColorDialog()
  4790. proj_color = c_dialog.getColor(initial=current_color)
  4791. if proj_color.isValid() is False:
  4792. return
  4793. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  4794. "background-color:%s" % str(proj_color.name()))
  4795. new_val_sel = str(proj_color.name())
  4796. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  4797. self.defaults['global_proj_item_color'] = new_val_sel
  4798. def on_proj_color_dis_entry(self):
  4799. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  4800. .proj_color_dis_entry.get_value()
  4801. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  4802. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  4803. def on_proj_color_dis_button(self):
  4804. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  4805. c_dialog = QtWidgets.QColorDialog()
  4806. proj_color = c_dialog.getColor(initial=current_color)
  4807. if proj_color.isValid() is False:
  4808. return
  4809. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  4810. "background-color:%s" % str(proj_color.name()))
  4811. new_val_sel = str(proj_color.name())
  4812. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  4813. self.defaults['global_proj_item_dis_color'] = new_val_sel
  4814. def on_annotation_fontcolor_entry(self):
  4815. self.defaults['cncjob_annotation_fontcolor'] = \
  4816. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  4817. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  4818. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  4819. def on_annotation_fontcolor_button(self):
  4820. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  4821. c_dialog = QtWidgets.QColorDialog()
  4822. annotation_color = c_dialog.getColor(initial=current_color)
  4823. if annotation_color.isValid() is False:
  4824. return
  4825. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  4826. "background-color:%s" % str(annotation_color.name()))
  4827. new_val_sel = str(annotation_color.name())
  4828. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  4829. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  4830. def on_film_color_entry(self):
  4831. self.defaults['tools_film_color'] = \
  4832. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  4833. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  4834. "background-color:%s" % str(self.defaults['tools_film_color']))
  4835. def on_film_color_button(self):
  4836. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  4837. c_dialog = QtWidgets.QColorDialog()
  4838. film_color = c_dialog.getColor(initial=current_color)
  4839. if film_color.isValid() is False:
  4840. return
  4841. # if new color is different then mark that the Preferences are changed
  4842. if film_color != current_color:
  4843. self.on_preferences_edited()
  4844. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  4845. "background-color:%s" % str(film_color.name()))
  4846. new_val_sel = str(film_color.name())
  4847. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  4848. self.defaults['tools_film_color'] = new_val_sel
  4849. def on_splash_changed(self, state):
  4850. settings = QSettings("Open Source", "FlatCAM")
  4851. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  4852. # This will write the setting to the platform specific storage.
  4853. del settings
  4854. def on_notebook_tab_rmb_click(self, checked):
  4855. self.ui.notebook.set_detachable(val=checked)
  4856. self.defaults["global_tabs_detachable"] = checked
  4857. self.ui.plot_tab_area.set_detachable(val=checked)
  4858. self.defaults["global_tabs_detachable"] = checked
  4859. def on_deselect_all(self):
  4860. self.collection.set_all_inactive()
  4861. self.delete_selection_shape()
  4862. def on_workspace_modified(self):
  4863. self.save_defaults(silent=True)
  4864. self.plotcanvas.draw_workspace()
  4865. def on_workspace(self):
  4866. self.report_usage("on_workspace()")
  4867. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  4868. self.plotcanvas.restore_workspace()
  4869. else:
  4870. self.plotcanvas.delete_workspace()
  4871. self.save_defaults(silent=True)
  4872. def on_workspace_menu(self):
  4873. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  4874. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  4875. else:
  4876. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  4877. self.on_workspace()
  4878. def on_layout(self, index=None, lay=None):
  4879. self.report_usage("on_layout()")
  4880. if lay:
  4881. current_layout = lay
  4882. else:
  4883. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  4884. settings = QSettings("Open Source", "FlatCAM")
  4885. settings.setValue('layout', current_layout)
  4886. # This will write the setting to the platform specific storage.
  4887. del settings
  4888. # first remove the toolbars:
  4889. try:
  4890. self.ui.removeToolBar(self.ui.toolbarfile)
  4891. self.ui.removeToolBar(self.ui.toolbargeo)
  4892. self.ui.removeToolBar(self.ui.toolbarview)
  4893. self.ui.removeToolBar(self.ui.toolbarshell)
  4894. self.ui.removeToolBar(self.ui.toolbartools)
  4895. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  4896. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  4897. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  4898. self.ui.removeToolBar(self.ui.snap_toolbar)
  4899. self.ui.removeToolBar(self.ui.toolbarshell)
  4900. except Exception as e:
  4901. pass
  4902. if current_layout == 'standard':
  4903. # ## TOOLBAR INSTALLATION # ##
  4904. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  4905. self.ui.toolbarfile.setObjectName('File_TB')
  4906. self.ui.addToolBar(self.ui.toolbarfile)
  4907. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  4908. self.ui.toolbargeo.setObjectName('Edit_TB')
  4909. self.ui.addToolBar(self.ui.toolbargeo)
  4910. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  4911. self.ui.toolbarview.setObjectName('View_TB')
  4912. self.ui.addToolBar(self.ui.toolbarview)
  4913. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  4914. self.ui.toolbarshell.setObjectName('Shell_TB')
  4915. self.ui.addToolBar(self.ui.toolbarshell)
  4916. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  4917. self.ui.toolbartools.setObjectName('Tools_TB')
  4918. self.ui.addToolBar(self.ui.toolbartools)
  4919. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  4920. # self.ui.exc_edit_toolbar.setVisible(False)
  4921. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  4922. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  4923. self.ui.addToolBarBreak()
  4924. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  4925. # self.ui.geo_edit_toolbar.setVisible(False)
  4926. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  4927. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  4928. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  4929. # self.ui.grb_edit_toolbar.setVisible(False)
  4930. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  4931. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  4932. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  4933. self.ui.snap_toolbar.setObjectName('Snap_TB')
  4934. # self.ui.snap_toolbar.setMaximumHeight(30)
  4935. self.ui.addToolBar(self.ui.snap_toolbar)
  4936. self.ui.corner_snap_btn.setVisible(False)
  4937. self.ui.snap_magnet.setVisible(False)
  4938. elif current_layout == 'compact':
  4939. # ## TOOLBAR INSTALLATION # ##
  4940. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  4941. self.ui.toolbarfile.setObjectName('File_TB')
  4942. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  4943. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  4944. self.ui.toolbargeo.setObjectName('Edit_TB')
  4945. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  4946. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  4947. self.ui.toolbarshell.setObjectName('Shell_TB')
  4948. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  4949. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  4950. self.ui.toolbartools.setObjectName('Tools_TB')
  4951. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  4952. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  4953. # self.ui.geo_edit_toolbar.setVisible(False)
  4954. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  4955. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  4956. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  4957. self.ui.toolbarview.setObjectName('View_TB')
  4958. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  4959. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  4960. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  4961. # self.ui.grb_edit_toolbar.setVisible(False)
  4962. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  4963. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  4964. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  4965. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  4966. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  4967. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  4968. self.ui.snap_toolbar.setObjectName('Snap_TB')
  4969. self.ui.snap_toolbar.setMaximumHeight(30)
  4970. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  4971. self.ui.corner_snap_btn.setVisible(True)
  4972. self.ui.snap_magnet.setVisible(True)
  4973. # add all the actions to the toolbars
  4974. self.ui.populate_toolbars()
  4975. # reconnect all the signals to the toolbar actions
  4976. self.connect_toolbar_signals()
  4977. self.ui.grid_snap_btn.setChecked(True)
  4978. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  4979. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  4980. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  4981. self.ui.grid_gap_link_cb.setChecked(True)
  4982. def on_cnc_custom_parameters(self, signal_text):
  4983. if signal_text == 'Parameters':
  4984. return
  4985. else:
  4986. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  4987. def on_save_button(self):
  4988. log.debug("App.on_save_button() --> Saving preferences to file.")
  4989. self.preferences_changed_flag = False
  4990. self.save_defaults(silent=False)
  4991. # load the defaults so they are updated into the app
  4992. self.load_defaults(filename='current_defaults')
  4993. # Re-fresh project options
  4994. self.on_options_app2project()
  4995. # save the notebook font size
  4996. settings = QSettings("Open Source", "FlatCAM")
  4997. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4998. settings.setValue('notebook_font_size', fsize)
  4999. # save the axis font size
  5000. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5001. settings.setValue('axis_font_size', g_fsize)
  5002. # This will write the setting to the platform specific storage.
  5003. del settings
  5004. def handlePrint(self):
  5005. self.report_usage("handlePrint()")
  5006. dialog = QtPrintSupport.QPrintDialog()
  5007. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  5008. self.ui.code_editor.document().print_(dialog.printer())
  5009. def handlePreview(self):
  5010. self.report_usage("handlePreview()")
  5011. dialog = QtPrintSupport.QPrintPreviewDialog()
  5012. dialog.paintRequested.connect(self.ui.code_editor.print_)
  5013. dialog.exec_()
  5014. def handleTextChanged(self):
  5015. # enable = not self.ui.code_editor.document().isEmpty()
  5016. # self.ui.buttonPrint.setEnabled(enable)
  5017. # self.ui.buttonPreview.setEnabled(enable)
  5018. pass
  5019. def handleOpen(self, filt=None):
  5020. self.report_usage("handleOpen()")
  5021. if filt:
  5022. _filter_ = filt
  5023. else:
  5024. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  5025. "All Files (*.*)"
  5026. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  5027. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  5028. if path:
  5029. file = QtCore.QFile(path)
  5030. if file.open(QtCore.QIODevice.ReadOnly):
  5031. stream = QtCore.QTextStream(file)
  5032. self.gcode_edited = stream.readAll()
  5033. self.ui.code_editor.setPlainText(self.gcode_edited)
  5034. file.close()
  5035. def handleSaveGCode(self, name=None, filt=None):
  5036. self.report_usage("handleSaveGCode()")
  5037. if filt:
  5038. _filter_ = filt
  5039. else:
  5040. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  5041. "All Files (*.*)"
  5042. if name:
  5043. obj_name = name
  5044. else:
  5045. try:
  5046. obj_name = self.collection.get_active().options['name']
  5047. except AttributeError:
  5048. obj_name = 'file'
  5049. if filt is None:
  5050. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  5051. try:
  5052. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  5053. caption=_("Export G-Code ..."),
  5054. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  5055. filter=_filter_
  5056. )[0])
  5057. except TypeError:
  5058. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  5059. if filename == "":
  5060. self.inform.emit('[WARNING_NOTCL] %s' %
  5061. _("Export Code cancelled."))
  5062. return
  5063. else:
  5064. try:
  5065. my_gcode = self.ui.code_editor.toPlainText()
  5066. with open(filename, 'w') as f:
  5067. for line in my_gcode:
  5068. f.write(line)
  5069. except FileNotFoundError:
  5070. self.inform.emit('[WARNING] %s' %
  5071. _("No such file or directory"))
  5072. return
  5073. except PermissionError:
  5074. self.inform.emit('[WARNING] %s' %
  5075. _("Permission denied, saving not possible.\n"
  5076. "Most likely another app is holding the file open and not accessible."))
  5077. return
  5078. # Just for adding it to the recent files list.
  5079. if self.defaults["global_open_style"] is False:
  5080. self.file_opened.emit("cncjob", filename)
  5081. self.file_saved.emit("cncjob", filename)
  5082. self.inform.emit('%s: %s' % (_("Saved to"), str(filename)))
  5083. def handleFindGCode(self):
  5084. self.report_usage("handleFindGCode()")
  5085. flags = QtGui.QTextDocument.FindCaseSensitively
  5086. text_to_be_found = self.ui.entryFind.get_value()
  5087. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  5088. if r is False:
  5089. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5090. def handleReplaceGCode(self):
  5091. self.report_usage("handleReplaceGCode()")
  5092. old = self.ui.entryFind.get_value()
  5093. new = self.ui.entryReplace.get_value()
  5094. if self.ui.sel_all_cb.isChecked():
  5095. while True:
  5096. cursor = self.ui.code_editor.textCursor()
  5097. cursor.beginEditBlock()
  5098. flags = QtGui.QTextDocument.FindCaseSensitively
  5099. # self.ui.editor is the QPlainTextEdit
  5100. r = self.ui.code_editor.find(str(old), flags)
  5101. if r:
  5102. qc = self.ui.code_editor.textCursor()
  5103. if qc.hasSelection():
  5104. qc.insertText(new)
  5105. else:
  5106. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5107. break
  5108. # Mark end of undo block
  5109. cursor.endEditBlock()
  5110. else:
  5111. cursor = self.ui.code_editor.textCursor()
  5112. cursor.beginEditBlock()
  5113. qc = self.ui.code_editor.textCursor()
  5114. if qc.hasSelection():
  5115. qc.insertText(new)
  5116. # Mark end of undo block
  5117. cursor.endEditBlock()
  5118. def handleRunCode(self):
  5119. # trying to run a Tcl command without having the Shell open will create some warnings because the Tcl Shell
  5120. # tries to print on a hidden widget, therefore show the dock if hidden
  5121. if self.ui.shell_dock.isHidden():
  5122. self.ui.shell_dock.show()
  5123. self.script_code = deepcopy(self.ui.code_editor.toPlainText())
  5124. # self.shell._sysShell.exec_command(script_code)
  5125. old_line = ''
  5126. for tcl_command_line in self.script_code.splitlines():
  5127. # do not process lines starting with '#' = comment and empty lines
  5128. if not tcl_command_line.startswith('#') and tcl_command_line != '':
  5129. # id FlatCAM is run in Windows then replace all the slashes with
  5130. # the UNIX style slash that TCL understands
  5131. if sys.platform == 'win32':
  5132. if "open" in tcl_command_line:
  5133. tcl_command_line = tcl_command_line.replace('\\', '/')
  5134. if old_line != '':
  5135. new_command = old_line + tcl_command_line + '\n'
  5136. else:
  5137. new_command = tcl_command_line
  5138. # execute the actual Tcl command
  5139. try:
  5140. self.shell.open_proccessing() # Disables input box.
  5141. result = self.tcl.eval(str(new_command))
  5142. if result != 'None':
  5143. self.shell.append_output(result + '\n')
  5144. old_line = ''
  5145. except tk.TclError:
  5146. old_line = old_line + tcl_command_line + '\n'
  5147. except Exception as e:
  5148. log.debug("App.handleRunCode() --> %s" % str(e))
  5149. if old_line != '':
  5150. # it means that the script finished with an error
  5151. result = self.tcl.eval("set errorInfo")
  5152. self.log.error("Exec command Exception: %s" % (result + '\n'))
  5153. self.shell.append_error('ERROR: ' + result + '\n')
  5154. self.shell.close_proccessing()
  5155. def on_tool_add_keypress(self):
  5156. # ## Current application units in Upper Case
  5157. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5158. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5159. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5160. if notebook_widget_name == 'selected_tab':
  5161. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5162. # Tool add works for Geometry only if Advanced is True in Preferences
  5163. if self.defaults["global_app_level"] == 'a':
  5164. tool_add_popup = FCInputDialog(title="New Tool ...",
  5165. text='Enter a Tool Diameter:',
  5166. min=0.0000, max=99.9999, decimals=4)
  5167. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5168. val, ok = tool_add_popup.get_value()
  5169. if ok:
  5170. if float(val) == 0:
  5171. self.inform.emit('[WARNING_NOTCL] %s' %
  5172. _("Please enter a tool diameter with non-zero value, in Float format."))
  5173. return
  5174. self.collection.get_active().on_tool_add(dia=float(val))
  5175. else:
  5176. self.inform.emit('[WARNING_NOTCL] %s...' %
  5177. _("Adding Tool cancelled"))
  5178. else:
  5179. msgbox = QtWidgets.QMessageBox()
  5180. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5181. "Go to Preferences -> General - Show Advanced Options."))
  5182. msgbox.setWindowTitle("Tool adding ...")
  5183. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5184. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5185. msgbox.setDefaultButton(bt_ok)
  5186. msgbox.exec_()
  5187. # work only if the notebook tab on focus is the Tools_Tab
  5188. if notebook_widget_name == 'tool_tab':
  5189. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5190. tool_add_popup = FCInputDialog(title="New Tool ...",
  5191. text='Enter a Tool Diameter:',
  5192. min=0.0000, max=99.9999, decimals=4)
  5193. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5194. val, ok = tool_add_popup.get_value()
  5195. # and only if the tool is NCC Tool
  5196. if tool_widget == self.ncclear_tool.toolName:
  5197. if ok:
  5198. if float(val) == 0:
  5199. self.inform.emit('[WARNING_NOTCL] %s' %
  5200. _("Please enter a tool diameter with non-zero value, in Float format."))
  5201. return
  5202. self.ncclear_tool.on_tool_add(dia=float(val))
  5203. else:
  5204. self.inform.emit('[WARNING_NOTCL] %s...' %
  5205. _("Adding Tool cancelled"))
  5206. # and only if the tool is Paint Area Tool
  5207. elif tool_widget == self.paint_tool.toolName:
  5208. if ok:
  5209. if float(val) == 0:
  5210. self.inform.emit('[WARNING_NOTCL] %s' %
  5211. _("Please enter a tool diameter with non-zero value, in Float format."))
  5212. return
  5213. self.paint_tool.on_tool_add(dia=float(val))
  5214. else:
  5215. self.inform.emit('[WARNING_NOTCL] %s...' %
  5216. _("Adding Tool cancelled"))
  5217. # and only if the tool is Solder Paste Dispensing Tool
  5218. elif tool_widget == self.paste_tool.toolName:
  5219. if ok:
  5220. if float(val) == 0:
  5221. self.inform.emit('[WARNING_NOTCL] %s' %
  5222. _("Please enter a tool diameter with non-zero value, in Float format."))
  5223. return
  5224. self.paste_tool.on_tool_add(dia=float(val))
  5225. else:
  5226. self.inform.emit('[WARNING_NOTCL] %s...' %
  5227. _("Adding Tool cancelled"))
  5228. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5229. # See description bellow.
  5230. def on_delete_keypress(self):
  5231. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5232. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5233. if notebook_widget_name == 'selected_tab':
  5234. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5235. self.collection.get_active().on_tool_delete()
  5236. # work only if the notebook tab on focus is the Tools_Tab
  5237. elif notebook_widget_name == 'tool_tab':
  5238. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5239. # and only if the tool is NCC Tool
  5240. if tool_widget == self.ncclear_tool.toolName:
  5241. self.ncclear_tool.on_tool_delete()
  5242. # and only if the tool is Paint Tool
  5243. elif tool_widget == self.paint_tool.toolName:
  5244. self.paint_tool.on_tool_delete()
  5245. # and only if the tool is Solder Paste Dispensing Tool
  5246. elif tool_widget == self.paste_tool.toolName:
  5247. self.paste_tool.on_tool_delete()
  5248. else:
  5249. self.on_delete()
  5250. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5251. # some screens you have to be careful where you hover with your mouse.
  5252. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5253. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5254. # Complicated, I know :)
  5255. def on_delete(self):
  5256. """
  5257. Delete the currently selected FlatCAMObjs.
  5258. :return: None
  5259. """
  5260. self.report_usage("on_delete()")
  5261. response = None
  5262. bt_ok = None
  5263. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5264. # a geometry object before we update it.
  5265. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5266. and self.grb_editor.editor_active is False:
  5267. if self.defaults["global_delete_confirmation"] is True:
  5268. msgbox = QtWidgets.QMessageBox()
  5269. msgbox.setWindowTitle(_("Delete objects"))
  5270. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5271. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5272. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5273. "the selected objects?"))
  5274. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5275. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5276. msgbox.setDefaultButton(bt_ok)
  5277. msgbox.exec_()
  5278. response = msgbox.clickedButton()
  5279. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5280. if self.collection.get_active():
  5281. self.log.debug("App.on_delete()")
  5282. while self.collection.get_active():
  5283. obj_active = self.collection.get_active()
  5284. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5285. if isinstance(obj_active, FlatCAMGerber):
  5286. for el in obj_active.mark_shapes:
  5287. obj_active.mark_shapes[el].clear(update=True)
  5288. obj_active.mark_shapes[el].enabled = False
  5289. # obj_active.mark_shapes[el] = None
  5290. del el
  5291. elif isinstance(obj_active, FlatCAMCNCjob):
  5292. try:
  5293. obj_active.annotation.clear(update=True)
  5294. obj_active.annotation.enabled = False
  5295. except AttributeError:
  5296. pass
  5297. self.delete_first_selected()
  5298. self.inform.emit('%s...' %
  5299. _("Object(s) deleted"))
  5300. # make sure that the selection shape is deleted, too
  5301. self.delete_selection_shape()
  5302. else:
  5303. self.inform.emit(_("Failed. No object(s) selected..."))
  5304. else:
  5305. self.inform.emit(_("Save the work in Editor and try again ..."))
  5306. def delete_first_selected(self):
  5307. # Keep this for later
  5308. try:
  5309. sel_obj = self.collection.get_active()
  5310. name = sel_obj.options["name"]
  5311. except AttributeError:
  5312. self.log.debug("Nothing selected for deletion")
  5313. return
  5314. # Remove from dictionary
  5315. self.collection.delete_active()
  5316. # Clear form
  5317. self.setup_component_editor()
  5318. self.inform.emit('%s: %s' %
  5319. (_("Object deleted"), name))
  5320. def on_set_origin(self):
  5321. """
  5322. Set the origin to the left mouse click position
  5323. :return: None
  5324. """
  5325. # display the message for the user
  5326. # and ask him to click on the desired position
  5327. self.report_usage("on_set_origin()")
  5328. def origin_replot():
  5329. def worker_task():
  5330. with self.proc_container.new('%s...' % _("Plotting")):
  5331. for obj in self.collection.get_list():
  5332. obj.plot()
  5333. self.plotcanvas.fit_view()
  5334. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  5335. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5336. self.inform.emit(_('Click to set the origin ...'))
  5337. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  5338. # first disconnect it as it may have been used by something else
  5339. try:
  5340. self.replot_signal.disconnect()
  5341. except TypeError:
  5342. pass
  5343. self.replot_signal[list].connect(origin_replot)
  5344. def on_set_zero_click(self, event):
  5345. # this function will be available only for mouse left click
  5346. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5347. if event.button == 1:
  5348. if self.grid_status() == True:
  5349. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5350. else:
  5351. pos = pos_canvas
  5352. x = 0 - pos[0]
  5353. y = 0 - pos[1]
  5354. def worker_task():
  5355. with self.proc_container.new(_("Setting Origin...")):
  5356. for obj in self.collection.get_list():
  5357. obj.offset((x, y))
  5358. self.object_changed.emit(obj)
  5359. # Update the object bounding box options
  5360. a, b, c, d = obj.bounds()
  5361. obj.options['xmin'] = a
  5362. obj.options['ymin'] = b
  5363. obj.options['xmax'] = c
  5364. obj.options['ymax'] = d
  5365. self.inform.emit('[success]%s...' %
  5366. _('Origin set'))
  5367. self.replot_signal.emit([])
  5368. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5369. self.should_we_save = True
  5370. def on_jump_to(self, custom_location=None, fit_center=True):
  5371. """
  5372. Jump to a location by setting the mouse cursor location
  5373. :return:
  5374. """
  5375. self.report_usage("on_jump_to()")
  5376. if not custom_location:
  5377. dia_box = Dialog_box(title=_("Jump to ..."),
  5378. label=_("Enter the coordinates in format X,Y:"),
  5379. icon=QtGui.QIcon('share/jump_to16.png'))
  5380. if dia_box.ok is True:
  5381. try:
  5382. location = eval(dia_box.location)
  5383. if not isinstance(location, tuple):
  5384. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  5385. return
  5386. except:
  5387. return
  5388. else:
  5389. return
  5390. else:
  5391. location = custom_location
  5392. if fit_center:
  5393. self.plotcanvas.fit_center(loc=location)
  5394. cursor = QtGui.QCursor()
  5395. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5396. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  5397. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  5398. self.inform.emit('[success] %s' %
  5399. _("Done."))
  5400. return location
  5401. def on_copy_object(self):
  5402. self.report_usage("on_copy_object()")
  5403. def initialize(obj_init, app):
  5404. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5405. try:
  5406. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5407. except AttributeError:
  5408. pass
  5409. try:
  5410. obj_init.apertures = deepcopy(obj.apertures)
  5411. except AttributeError:
  5412. pass
  5413. try:
  5414. if obj.tools:
  5415. obj_init.tools = deepcopy(obj.tools)
  5416. except Exception as e:
  5417. log.debug("App.on_copy_object() --> %s" % str(e))
  5418. def initialize_excellon(obj_init, app):
  5419. obj_init.tools = deepcopy(obj.tools)
  5420. # drills are offset, so they need to be deep copied
  5421. obj_init.drills = deepcopy(obj.drills)
  5422. # slots are offset, so they need to be deep copied
  5423. obj_init.slots = deepcopy(obj.slots)
  5424. obj_init.create_geometry()
  5425. for obj in self.collection.get_selected():
  5426. obj_name = obj.options["name"]
  5427. try:
  5428. if isinstance(obj, FlatCAMExcellon):
  5429. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  5430. elif isinstance(obj, FlatCAMGerber):
  5431. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  5432. elif isinstance(obj, FlatCAMGeometry):
  5433. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  5434. except Exception as e:
  5435. return "Operation failed: %s" % str(e)
  5436. def on_copy_object2(self, custom_name):
  5437. def initialize_geometry(obj_init, app):
  5438. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5439. try:
  5440. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5441. except AttributeError:
  5442. pass
  5443. try:
  5444. obj_init.apertures = deepcopy(obj.apertures)
  5445. except AttributeError:
  5446. pass
  5447. try:
  5448. if obj.tools:
  5449. obj_init.tools = deepcopy(obj.tools)
  5450. except Exception as e:
  5451. log.debug("on_copy_object2() --> %s" % str(e))
  5452. def initialize_gerber(obj_init, app):
  5453. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5454. obj_init.apertures = deepcopy(obj.apertures)
  5455. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  5456. def initialize_excellon(obj_init, app):
  5457. obj_init.tools = deepcopy(obj.tools)
  5458. # drills are offset, so they need to be deep copied
  5459. obj_init.drills = deepcopy(obj.drills)
  5460. # slots are offset, so they need to be deep copied
  5461. obj_init.slots = deepcopy(obj.slots)
  5462. obj_init.create_geometry()
  5463. for obj in self.collection.get_selected():
  5464. obj_name = obj.options["name"]
  5465. try:
  5466. if isinstance(obj, FlatCAMExcellon):
  5467. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  5468. elif isinstance(obj, FlatCAMGerber):
  5469. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  5470. elif isinstance(obj, FlatCAMGeometry):
  5471. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  5472. except Exception as e:
  5473. return "Operation failed: %s" % str(e)
  5474. def on_rename_object(self, text):
  5475. self.report_usage("on_rename_object()")
  5476. named_obj = self.collection.get_active()
  5477. for obj in named_obj:
  5478. if obj is list:
  5479. self.on_rename_object(text)
  5480. else:
  5481. try:
  5482. obj.options['name'] = text
  5483. except Exception as e:
  5484. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  5485. def convert_any2geo(self):
  5486. self.report_usage("convert_any2geo()")
  5487. def initialize(obj_init, app):
  5488. obj_init.solid_geometry = obj.solid_geometry
  5489. try:
  5490. obj_init.follow_geometry = obj.follow_geometry
  5491. except AttributeError:
  5492. pass
  5493. try:
  5494. obj_init.apertures = obj.apertures
  5495. except AttributeError:
  5496. pass
  5497. try:
  5498. if obj.tools:
  5499. obj_init.tools = obj.tools
  5500. except AttributeError:
  5501. pass
  5502. def initialize_excellon(obj_init, app):
  5503. # objs = self.collection.get_selected()
  5504. # FlatCAMGeometry.merge(objs, obj)
  5505. solid_geo = []
  5506. for tool in obj.tools:
  5507. for geo in obj.tools[tool]['solid_geometry']:
  5508. solid_geo.append(geo)
  5509. obj_init.solid_geometry = deepcopy(solid_geo)
  5510. if not self.collection.get_selected():
  5511. log.warning("App.convert_any2geo --> No object selected")
  5512. self.inform.emit('[WARNING_NOTCL] %s' %
  5513. _("No object is selected. Select an object and try again."))
  5514. return
  5515. for obj in self.collection.get_selected():
  5516. obj_name = obj.options["name"]
  5517. try:
  5518. if isinstance(obj, FlatCAMExcellon):
  5519. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  5520. else:
  5521. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  5522. except Exception as e:
  5523. return "Operation failed: %s" % str(e)
  5524. def convert_any2gerber(self):
  5525. self.report_usage("convert_any2gerber()")
  5526. def initialize_geometry(obj_init, app):
  5527. apertures = {}
  5528. apid = 0
  5529. apertures[str(apid)] = {}
  5530. apertures[str(apid)]['geometry'] = []
  5531. for obj_orig in obj.solid_geometry:
  5532. new_elem = dict()
  5533. new_elem['solid'] = obj_orig
  5534. new_elem['follow'] = obj_orig.exterior
  5535. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  5536. apertures[str(apid)]['size'] = 0.0
  5537. apertures[str(apid)]['type'] = 'C'
  5538. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5539. obj_init.apertures = deepcopy(apertures)
  5540. def initialize_excellon(obj_init, app):
  5541. apertures = {}
  5542. apid = 10
  5543. for tool in obj.tools:
  5544. apertures[str(apid)] = {}
  5545. apertures[str(apid)]['geometry'] = []
  5546. for geo in obj.tools[tool]['solid_geometry']:
  5547. new_el = dict()
  5548. new_el['solid'] = geo
  5549. new_el['follow'] = geo.exterior
  5550. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  5551. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  5552. apertures[str(apid)]['type'] = 'C'
  5553. apid += 1
  5554. # create solid_geometry
  5555. solid_geometry = []
  5556. for apid in apertures:
  5557. for geo_el in apertures[apid]['geometry']:
  5558. solid_geometry.append(geo_el['solid'])
  5559. solid_geometry = MultiPolygon(solid_geometry)
  5560. solid_geometry = solid_geometry.buffer(0.0000001)
  5561. obj_init.solid_geometry = deepcopy(solid_geometry)
  5562. obj_init.apertures = deepcopy(apertures)
  5563. # clear the working objects (perhaps not necessary due of Python GC)
  5564. apertures.clear()
  5565. if not self.collection.get_selected():
  5566. log.warning("App.convert_any2gerber --> No object selected")
  5567. self.inform.emit('[WARNING_NOTCL] %s' %
  5568. _("No object is selected. Select an object and try again."))
  5569. return
  5570. for obj in self.collection.get_selected():
  5571. obj_name = obj.options["name"]
  5572. try:
  5573. if isinstance(obj, FlatCAMExcellon):
  5574. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  5575. elif isinstance(obj, FlatCAMGeometry):
  5576. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  5577. else:
  5578. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  5579. except Exception as e:
  5580. return "Operation failed: %s" % str(e)
  5581. def abort_all_tasks(self):
  5582. if self.abort_flag is False:
  5583. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  5584. self.abort_flag = True
  5585. def app_is_idle(self):
  5586. if self.abort_flag:
  5587. self.inform.emit('[WARNING_NOTCL] %s' %
  5588. _("The current task was gracefully closed on user request..."))
  5589. self.abort_flag = False
  5590. def on_selectall(self):
  5591. self.report_usage("on_selectall()")
  5592. # delete the possible selection box around a possible selected object
  5593. self.delete_selection_shape()
  5594. for name in self.collection.get_names():
  5595. self.collection.set_active(name)
  5596. curr_sel_obj = self.collection.get_by_name(name)
  5597. # create the selection box around the selected object
  5598. if self.defaults['global_selection_shape'] is True:
  5599. self.draw_selection_shape(curr_sel_obj)
  5600. def on_preferences(self):
  5601. # add the tab if it was closed
  5602. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  5603. # delete the absolute and relative position and messages in the infobar
  5604. self.ui.position_label.setText("")
  5605. self.ui.rel_position_label.setText("")
  5606. # Switch plot_area to preferences page
  5607. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  5608. # self.ui.show()
  5609. # this disconnect() is done so the slot will be connected only once
  5610. try:
  5611. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_preferences_closed)
  5612. except (TypeError, AttributeError):
  5613. pass
  5614. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_preferences_closed)
  5615. # detect changes in the preferences
  5616. for idx in range(self.ui.pref_tab_area.count()):
  5617. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5618. try:
  5619. try:
  5620. tb.textEdited.disconnect(self.on_preferences_edited)
  5621. except (TypeError, AttributeError):
  5622. pass
  5623. tb.textEdited.connect(self.on_preferences_edited)
  5624. except AttributeError:
  5625. pass
  5626. try:
  5627. try:
  5628. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5629. except (TypeError, AttributeError):
  5630. pass
  5631. tb.modificationChanged.connect(self.on_preferences_edited)
  5632. except AttributeError:
  5633. pass
  5634. try:
  5635. try:
  5636. tb.toggled.disconnect(self.on_preferences_edited)
  5637. except (TypeError, AttributeError):
  5638. pass
  5639. tb.toggled.connect(self.on_preferences_edited)
  5640. except AttributeError:
  5641. pass
  5642. try:
  5643. try:
  5644. tb.valueChanged.disconnect(self.on_preferences_edited)
  5645. except (TypeError, AttributeError):
  5646. pass
  5647. tb.valueChanged.connect(self.on_preferences_edited)
  5648. except AttributeError:
  5649. pass
  5650. try:
  5651. try:
  5652. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5653. except (TypeError, AttributeError):
  5654. pass
  5655. tb.currentIndexChanged.connect(self.on_preferences_edited)
  5656. except AttributeError:
  5657. pass
  5658. def on_preferences_edited(self):
  5659. self.inform.emit('[WARNING_NOTCL] %s' %
  5660. _("Preferences edited but not saved."))
  5661. self.preferences_changed_flag = True
  5662. def on_preferences_closed(self):
  5663. # disconnect
  5664. for idx in range(self.ui.pref_tab_area.count()):
  5665. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5666. try:
  5667. tb.textEdited.disconnect(self.on_preferences_edited)
  5668. except (TypeError, AttributeError):
  5669. pass
  5670. try:
  5671. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5672. except (TypeError, AttributeError):
  5673. pass
  5674. try:
  5675. tb.toggled.disconnect(self.on_preferences_edited)
  5676. except (TypeError, AttributeError):
  5677. pass
  5678. try:
  5679. tb.valueChanged.disconnect(self.on_preferences_edited)
  5680. except (TypeError, AttributeError):
  5681. pass
  5682. try:
  5683. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5684. except (TypeError, AttributeError):
  5685. pass
  5686. if self.preferences_changed_flag is True:
  5687. msgbox = QtWidgets.QMessageBox()
  5688. msgbox.setText(_("One or more values are changed.\n"
  5689. "Do you want to save the Preferences?"))
  5690. msgbox.setWindowTitle(_("Save Preferences"))
  5691. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  5692. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5693. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5694. msgbox.setDefaultButton(bt_yes)
  5695. msgbox.exec_()
  5696. response = msgbox.clickedButton()
  5697. if response == bt_yes:
  5698. self.on_save_button()
  5699. self.inform.emit('[success] %s' %
  5700. _("Preferences saved."))
  5701. else:
  5702. self.preferences_changed_flag = False
  5703. return
  5704. def on_flipy(self):
  5705. self.report_usage("on_flipy()")
  5706. obj_list = self.collection.get_selected()
  5707. xminlist = []
  5708. yminlist = []
  5709. xmaxlist = []
  5710. ymaxlist = []
  5711. if not obj_list:
  5712. self.inform.emit('[WARNING_NOTCL] %s' %
  5713. _("No object selected to Flip on Y axis."))
  5714. else:
  5715. try:
  5716. # first get a bounding box to fit all
  5717. for obj in obj_list:
  5718. xmin, ymin, xmax, ymax = obj.bounds()
  5719. xminlist.append(xmin)
  5720. yminlist.append(ymin)
  5721. xmaxlist.append(xmax)
  5722. ymaxlist.append(ymax)
  5723. # get the minimum x,y and maximum x,y for all objects selected
  5724. xminimal = min(xminlist)
  5725. yminimal = min(yminlist)
  5726. xmaximal = max(xmaxlist)
  5727. ymaximal = max(ymaxlist)
  5728. px = 0.5 * (xminimal + xmaximal)
  5729. py = 0.5 * (yminimal + ymaximal)
  5730. # execute mirroring
  5731. for obj in obj_list:
  5732. obj.mirror('X', [px, py])
  5733. obj.plot()
  5734. self.object_changed.emit(obj)
  5735. self.inform.emit('[success] %s' %
  5736. _("Flip on Y axis done."))
  5737. except Exception as e:
  5738. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5739. (_("Flip action was not executed."), str(e)))
  5740. return
  5741. def on_flipx(self):
  5742. self.report_usage("on_flipx()")
  5743. obj_list = self.collection.get_selected()
  5744. xminlist = []
  5745. yminlist = []
  5746. xmaxlist = []
  5747. ymaxlist = []
  5748. if not obj_list:
  5749. self.inform.emit('[WARNING_NOTCL] %s' %
  5750. _("No object selected to Flip on X axis."))
  5751. else:
  5752. try:
  5753. # first get a bounding box to fit all
  5754. for obj in obj_list:
  5755. xmin, ymin, xmax, ymax = obj.bounds()
  5756. xminlist.append(xmin)
  5757. yminlist.append(ymin)
  5758. xmaxlist.append(xmax)
  5759. ymaxlist.append(ymax)
  5760. # get the minimum x,y and maximum x,y for all objects selected
  5761. xminimal = min(xminlist)
  5762. yminimal = min(yminlist)
  5763. xmaximal = max(xmaxlist)
  5764. ymaximal = max(ymaxlist)
  5765. px = 0.5 * (xminimal + xmaximal)
  5766. py = 0.5 * (yminimal + ymaximal)
  5767. # execute mirroring
  5768. for obj in obj_list:
  5769. obj.mirror('Y', [px, py])
  5770. obj.plot()
  5771. self.object_changed.emit(obj)
  5772. self.inform.emit('[success] %s' %
  5773. _("Flip on X axis done."))
  5774. except Exception as e:
  5775. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5776. (_("Flip action was not executed."), str(e)))
  5777. return
  5778. def on_rotate(self, silent=False, preset=None):
  5779. self.report_usage("on_rotate()")
  5780. obj_list = self.collection.get_selected()
  5781. xminlist = []
  5782. yminlist = []
  5783. xmaxlist = []
  5784. ymaxlist = []
  5785. if not obj_list:
  5786. self.inform.emit('[WARNING_NOTCL] %s' %
  5787. _("No object selected to Rotate."))
  5788. else:
  5789. if silent is False:
  5790. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5791. min=-360, max=360, decimals=4,
  5792. init_val=float(self.defaults['tools_transform_rotate']))
  5793. num, ok = rotatebox.get_value()
  5794. else:
  5795. num = preset
  5796. ok = True
  5797. if ok:
  5798. try:
  5799. # first get a bounding box to fit all
  5800. for obj in obj_list:
  5801. xmin, ymin, xmax, ymax = obj.bounds()
  5802. xminlist.append(xmin)
  5803. yminlist.append(ymin)
  5804. xmaxlist.append(xmax)
  5805. ymaxlist.append(ymax)
  5806. # get the minimum x,y and maximum x,y for all objects selected
  5807. xminimal = min(xminlist)
  5808. yminimal = min(yminlist)
  5809. xmaximal = max(xmaxlist)
  5810. ymaximal = max(ymaxlist)
  5811. px = 0.5 * (xminimal + xmaximal)
  5812. py = 0.5 * (yminimal + ymaximal)
  5813. for sel_obj in obj_list:
  5814. sel_obj.rotate(-float(num), point=(px, py))
  5815. sel_obj.plot()
  5816. self.object_changed.emit(sel_obj)
  5817. self.inform.emit('[success] %s' %
  5818. _("Rotation done."))
  5819. except Exception as e:
  5820. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5821. (_("Rotation movement was not executed."), str(e)))
  5822. return
  5823. def on_skewx(self):
  5824. self.report_usage("on_skewx()")
  5825. obj_list = self.collection.get_selected()
  5826. xminlist = []
  5827. yminlist = []
  5828. if not obj_list:
  5829. self.inform.emit('[WARNING_NOTCL] %s' %
  5830. _("No object selected to Skew/Shear on X axis."))
  5831. else:
  5832. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5833. min=-360, max=360, decimals=4,
  5834. init_val=float(self.defaults['tools_transform_skew_x']))
  5835. num, ok = skewxbox.get_value()
  5836. if ok:
  5837. # first get a bounding box to fit all
  5838. for obj in obj_list:
  5839. xmin, ymin, xmax, ymax = obj.bounds()
  5840. xminlist.append(xmin)
  5841. yminlist.append(ymin)
  5842. # get the minimum x,y and maximum x,y for all objects selected
  5843. xminimal = min(xminlist)
  5844. yminimal = min(yminlist)
  5845. for obj in obj_list:
  5846. obj.skew(num, 0, point=(xminimal, yminimal))
  5847. obj.plot()
  5848. self.object_changed.emit(obj)
  5849. self.inform.emit('[success] %s' %
  5850. _("Skew on X axis done."))
  5851. def on_skewy(self):
  5852. self.report_usage("on_skewy()")
  5853. obj_list = self.collection.get_selected()
  5854. xminlist = []
  5855. yminlist = []
  5856. if not obj_list:
  5857. self.inform.emit('[WARNING_NOTCL] %s' %
  5858. _("No object selected to Skew/Shear on Y axis."))
  5859. else:
  5860. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5861. min=-360, max=360, decimals=4,
  5862. init_val=float(self.defaults['tools_transform_skew_y']))
  5863. num, ok = skewybox.get_value()
  5864. if ok:
  5865. # first get a bounding box to fit all
  5866. for obj in obj_list:
  5867. xmin, ymin, xmax, ymax = obj.bounds()
  5868. xminlist.append(xmin)
  5869. yminlist.append(ymin)
  5870. # get the minimum x,y and maximum x,y for all objects selected
  5871. xminimal = min(xminlist)
  5872. yminimal = min(yminlist)
  5873. for obj in obj_list:
  5874. obj.skew(0, num, point=(xminimal, yminimal))
  5875. obj.plot()
  5876. self.object_changed.emit(obj)
  5877. self.inform.emit('[success] %s' %
  5878. _("Skew on Y axis done."))
  5879. def on_plots_updated(self):
  5880. """
  5881. Callback used to report when the plots have changed.
  5882. Adjust axes and zooms to fit.
  5883. :return: None
  5884. """
  5885. self.plotcanvas.update() # TODO: Need update canvas?
  5886. self.on_zoom_fit(None)
  5887. self.collection.update_view()
  5888. # self.inform.emit(_("Plots updated ..."))
  5889. # TODO: Rework toolbar 'clear', 'replot' functions
  5890. def on_toolbar_replot(self):
  5891. """
  5892. Callback for toolbar button. Re-plots all objects.
  5893. :return: None
  5894. """
  5895. self.report_usage("on_toolbar_replot")
  5896. self.log.debug("on_toolbar_replot()")
  5897. try:
  5898. self.collection.get_active().read_form()
  5899. except AttributeError:
  5900. self.log.debug("on_toolbar_replot(): AttributeError")
  5901. pass
  5902. self.plot_all()
  5903. def on_row_activated(self, index):
  5904. if index.isValid():
  5905. if index.internalPointer().parent_item != self.collection.root_item:
  5906. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5907. self.collection.on_item_activated(index)
  5908. def grid_status(self):
  5909. if self.ui.grid_snap_btn.isChecked():
  5910. return True
  5911. else:
  5912. return False
  5913. def populate_cmenu_grids(self):
  5914. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5915. self.ui.cmenu_gridmenu.clear()
  5916. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5917. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  5918. grid_toggle.setCheckable(True)
  5919. if self.grid_status() == True:
  5920. grid_toggle.setChecked(True)
  5921. else:
  5922. grid_toggle.setChecked(False)
  5923. self.ui.cmenu_gridmenu.addSeparator()
  5924. for grid in sorted_list:
  5925. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  5926. action.triggered.connect(self.set_grid)
  5927. self.ui.cmenu_gridmenu.addSeparator()
  5928. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  5929. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  5930. grid_add.triggered.connect(self.on_grid_add)
  5931. grid_delete.triggered.connect(self.on_grid_delete)
  5932. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5933. def set_grid(self):
  5934. self.ui.grid_gap_x_entry.setText(self.sender().text())
  5935. self.ui.grid_gap_y_entry.setText(self.sender().text())
  5936. def on_grid_add(self):
  5937. # ## Current application units in lower Case
  5938. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5939. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5940. text=_('Enter a Grid Value:'),
  5941. min=0.0000, max=99.9999, decimals=4)
  5942. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  5943. val, ok = grid_add_popup.get_value()
  5944. if ok:
  5945. if float(val) == 0:
  5946. self.inform.emit('[WARNING_NOTCL] %s' %
  5947. _("Please enter a grid value with non-zero value, in Float format."))
  5948. return
  5949. else:
  5950. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5951. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5952. self.inform.emit('[success] %s...' %
  5953. _("New Grid added"))
  5954. else:
  5955. self.inform.emit('[WARNING_NOTCL] %s...' %
  5956. _("Grid already exists"))
  5957. else:
  5958. self.inform.emit('[WARNING_NOTCL] %s...' %
  5959. _("Adding New Grid cancelled"))
  5960. def on_grid_delete(self):
  5961. # ## Current application units in lower Case
  5962. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5963. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5964. text='Enter a Grid Value:',
  5965. min=0.0000, max=99.9999, decimals=4)
  5966. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  5967. val, ok = grid_del_popup.get_value()
  5968. if ok:
  5969. if float(val) == 0:
  5970. self.inform.emit('[WARNING_NOTCL] %s' %
  5971. _("Please enter a grid value with non-zero value, in Float format."))
  5972. return
  5973. else:
  5974. try:
  5975. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5976. except ValueError:
  5977. self.inform.emit('[ERROR_NOTCL]%s...' %
  5978. _(" Grid Value does not exist"))
  5979. return
  5980. self.inform.emit('[success] %s...' %
  5981. _("Grid Value deleted"))
  5982. else:
  5983. self.inform.emit('[WARNING_NOTCL] %s...' %
  5984. _("Delete Grid value cancelled"))
  5985. def on_shortcut_list(self):
  5986. self.report_usage("on_shortcut_list()")
  5987. # add the tab if it was closed
  5988. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5989. # delete the absolute and relative position and messages in the infobar
  5990. self.ui.position_label.setText("")
  5991. self.ui.rel_position_label.setText("")
  5992. # Switch plot_area to preferences page
  5993. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5994. # self.ui.show()
  5995. def on_select_tab(self, name):
  5996. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5997. if self.ui.splitter.sizes()[0] == 0:
  5998. self.ui.splitter.setSizes([1, 1])
  5999. else:
  6000. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  6001. self.ui.splitter.setSizes([0, 1])
  6002. if name == 'project':
  6003. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6004. elif name == 'selected':
  6005. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6006. elif name == 'tool':
  6007. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  6008. def on_copy_name(self):
  6009. self.report_usage("on_copy_name()")
  6010. obj = self.collection.get_active()
  6011. try:
  6012. name = obj.options["name"]
  6013. except AttributeError:
  6014. log.debug("on_copy_name() --> No object selected to copy it's name")
  6015. self.inform.emit('[WARNING_NOTCL]%s' %
  6016. _(" No object selected to copy it's name"))
  6017. return
  6018. self.clipboard.setText(name)
  6019. self.inform.emit(_("Name copied on clipboard ..."))
  6020. def on_mouse_click_over_plot(self, event):
  6021. """
  6022. Default actions are:
  6023. :param event: Contains information about the event, like which button
  6024. was clicked, the pixel coordinates and the axes coordinates.
  6025. :return: None
  6026. """
  6027. self.pos = []
  6028. # So it can receive key presses
  6029. self.plotcanvas.native.setFocus()
  6030. # Set the mouse button for panning
  6031. self.plotcanvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  6032. self.pos_canvas = self.plotcanvas.translate_coords(event.pos)
  6033. if self.grid_status() == True:
  6034. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  6035. self.app_cursor.enabled = True
  6036. else:
  6037. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  6038. self.app_cursor.enabled = False
  6039. try:
  6040. modifiers = QtWidgets.QApplication.keyboardModifiers()
  6041. if event.button == 1:
  6042. # Reset here the relative coordinates so there is a new reference on the click position
  6043. if self.rel_point1 is None:
  6044. self.rel_point1 = self.pos
  6045. else:
  6046. self.rel_point2 = copy(self.rel_point1)
  6047. self.rel_point1 = self.pos
  6048. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  6049. if modifiers == QtCore.Qt.ShiftModifier:
  6050. # do not auto open the Project Tab
  6051. self.click_noproject = True
  6052. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  6053. self.inform.emit('[success] %s' %
  6054. _("Coordinates copied to clipboard."))
  6055. return
  6056. self.on_mouse_move_over_plot(event, origin_click=True)
  6057. except Exception as e:
  6058. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  6059. def on_double_click_over_plot(self, event):
  6060. self.doubleclick = True
  6061. def on_mouse_move_over_plot(self, event, origin_click=None):
  6062. """
  6063. Callback for the mouse motion event over the plot.
  6064. :param event: Contains information about the event.
  6065. :param origin_click
  6066. :return: None
  6067. """
  6068. # So it can receive key presses
  6069. self.plotcanvas.native.setFocus()
  6070. self.pos_jump = event.pos
  6071. self.ui.popMenu.mouse_is_panning = False
  6072. if not origin_click:
  6073. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  6074. if event.button == 2 and event.is_dragging == 1:
  6075. self.ui.popMenu.mouse_is_panning = True
  6076. return
  6077. if self.rel_point1 is not None:
  6078. try: # May fail in case mouse not within axes
  6079. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  6080. if self.grid_status() == True:
  6081. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6082. self.app_cursor.enabled = True
  6083. # Update cursor
  6084. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  6085. else:
  6086. pos = (pos_canvas[0], pos_canvas[1])
  6087. self.app_cursor.enabled = False
  6088. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6089. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  6090. dx = pos[0] - self.rel_point1[0]
  6091. dy = pos[1] - self.rel_point1[1]
  6092. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6093. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6094. self.mouse = [pos[0], pos[1]]
  6095. # if the mouse is moved and the LMB is clicked then the action is a selection
  6096. if event.is_dragging == 1 and event.button == 1:
  6097. self.delete_selection_shape()
  6098. if dx < 0:
  6099. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  6100. face_color=self.defaults['global_alt_sel_fill'])
  6101. self.selection_type = False
  6102. else:
  6103. self.draw_moving_selection_shape(self.pos, pos)
  6104. self.selection_type = True
  6105. # hover effect - enabled in Preferences -> General -> GUI Settings
  6106. if self.defaults['global_hover']:
  6107. for obj in self.collection.get_list():
  6108. try:
  6109. # select the object(s) only if it is enabled (plotted)
  6110. if obj.options['plot']:
  6111. if obj not in self.collection.get_selected():
  6112. poly_obj = Polygon(
  6113. [(obj.options['xmin'], obj.options['ymin']),
  6114. (obj.options['xmax'], obj.options['ymin']),
  6115. (obj.options['xmax'], obj.options['ymax']),
  6116. (obj.options['xmin'], obj.options['ymax'])]
  6117. )
  6118. if Point(pos).within(poly_obj):
  6119. if obj.isHovering is False:
  6120. obj.isHovering = True
  6121. obj.notHovering = True
  6122. # create the selection box around the selected object
  6123. self.draw_hover_shape(obj, color='#d1e0e0')
  6124. else:
  6125. if obj.notHovering is True:
  6126. obj.notHovering = False
  6127. obj.isHovering = False
  6128. self.delete_hover_shape()
  6129. except:
  6130. # the Exception here will happen if we try to select on screen and we have an
  6131. # newly (and empty) just created Geometry or Excellon object that do not have the
  6132. # xmin, xmax, ymin, ymax options.
  6133. # In this case poly_obj creation (see above) will fail
  6134. pass
  6135. except:
  6136. self.ui.position_label.setText("")
  6137. self.ui.rel_position_label.setText("")
  6138. self.mouse = None
  6139. def on_mouse_click_release_over_plot(self, event):
  6140. """
  6141. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  6142. and has been registered in ''self.__init__()''.
  6143. :param event: contains information about the event.
  6144. :return:
  6145. """
  6146. pos = 0, 0
  6147. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  6148. if self.grid_status() == True:
  6149. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6150. else:
  6151. pos = (pos_canvas[0], pos_canvas[1])
  6152. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  6153. # canvas menu
  6154. if event.button == 2: # right click
  6155. if self.ui.popMenu.mouse_is_panning is False:
  6156. self.cursor = QtGui.QCursor()
  6157. self.populate_cmenu_grids()
  6158. self.ui.popMenu.popup(self.cursor.pos())
  6159. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  6160. # selection and then select a type of selection ("enclosing" or "touching")
  6161. try:
  6162. if event.button == 1: # left click
  6163. if self.doubleclick is True:
  6164. self.doubleclick = False
  6165. if self.collection.get_selected():
  6166. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6167. if self.ui.splitter.sizes()[0] == 0:
  6168. self.ui.splitter.setSizes([1, 1])
  6169. # delete the selection shape(S) as it may be in the way
  6170. self.delete_selection_shape()
  6171. self.delete_hover_shape()
  6172. else:
  6173. if self.selection_type is not None:
  6174. self.selection_area_handler(self.pos, pos, self.selection_type)
  6175. self.selection_type = None
  6176. else:
  6177. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  6178. if key_modifier == QtCore.Qt.ShiftModifier:
  6179. mod_key = 'Shift'
  6180. elif key_modifier == QtCore.Qt.ControlModifier:
  6181. mod_key = 'Control'
  6182. else:
  6183. mod_key = None
  6184. if mod_key == self.defaults["global_mselect_key"]:
  6185. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  6186. # deselect, and if it's not selected then it will be selected
  6187. # If there is no active command (self.command_active is None) then we check if we clicked
  6188. # on a object by checking the bounding limits against mouse click position
  6189. if self.command_active is None:
  6190. self.select_objects(key='CTRL')
  6191. self.delete_hover_shape()
  6192. else:
  6193. # If there is no active command (self.command_active is None) then we check if we clicked
  6194. # on a object by checking the bounding limits against mouse click position
  6195. if self.command_active is None:
  6196. self.select_objects()
  6197. self.delete_hover_shape()
  6198. except Exception as e:
  6199. log.warning("Error: %s" % str(e))
  6200. return
  6201. def selection_area_handler(self, start_pos, end_pos, sel_type):
  6202. """
  6203. :param start_pos: mouse position when the selection LMB click was done
  6204. :param end_pos: mouse position when the left mouse button is released
  6205. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  6206. :return:
  6207. """
  6208. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  6209. self.delete_selection_shape()
  6210. for obj in self.collection.get_list():
  6211. try:
  6212. # select the object(s) only if it is enabled (plotted)
  6213. if obj.options['plot']:
  6214. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  6215. (obj.options['xmax'], obj.options['ymin']),
  6216. (obj.options['xmax'], obj.options['ymax']),
  6217. (obj.options['xmin'], obj.options['ymax'])])
  6218. if sel_type is True:
  6219. if poly_obj.within(poly_selection):
  6220. # create the selection box around the selected object
  6221. if self.defaults['global_selection_shape'] is True:
  6222. self.draw_selection_shape(obj)
  6223. self.collection.set_active(obj.options['name'])
  6224. else:
  6225. if poly_selection.intersects(poly_obj):
  6226. # create the selection box around the selected object
  6227. if self.defaults['global_selection_shape'] is True:
  6228. self.draw_selection_shape(obj)
  6229. self.collection.set_active(obj.options['name'])
  6230. except Exception as e:
  6231. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  6232. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  6233. # In this case poly_obj creation (see above) will fail
  6234. log.debug("App.selection_area_handler() --> %s" % str(e))
  6235. def select_objects(self, key=None):
  6236. # list where we store the overlapped objects under our mouse left click position
  6237. objects_under_the_click_list = []
  6238. # Populate the list with the overlapped objects on the click position
  6239. curr_x, curr_y = self.pos
  6240. for obj in self.all_objects_list:
  6241. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  6242. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  6243. if obj.options['name'] not in objects_under_the_click_list:
  6244. if obj.options['plot']:
  6245. # add objects to the objects_under_the_click list only if the object is plotted
  6246. # (active and not disabled)
  6247. objects_under_the_click_list.append(obj.options['name'])
  6248. try:
  6249. # If there is no element in the overlapped objects list then make everyone inactive
  6250. # because we selected "nothing"
  6251. if not objects_under_the_click_list:
  6252. self.collection.set_all_inactive()
  6253. # delete the possible selection box around a possible selected object
  6254. self.delete_selection_shape()
  6255. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  6256. # only when working on App
  6257. if self.call_source == 'app':
  6258. if self.click_noproject is False:
  6259. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6260. else:
  6261. # restore auto open the Project Tab
  6262. self.click_noproject = False
  6263. # delete any text in the status bar, implicitly the last object name that was selected
  6264. self.inform.emit("")
  6265. else:
  6266. self.call_source = 'app'
  6267. else:
  6268. # case when there is only an object under the click and we toggle it
  6269. if len(objects_under_the_click_list) == 1:
  6270. if self.collection.get_active() is None:
  6271. self.collection.set_active(objects_under_the_click_list[0])
  6272. # create the selection box around the selected object
  6273. curr_sel_obj = self.collection.get_active()
  6274. if self.defaults['global_selection_shape'] is True:
  6275. self.draw_selection_shape(curr_sel_obj)
  6276. # self.inform.emit('[selected] %s: %s selected' %
  6277. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6278. if curr_sel_obj.kind == 'gerber':
  6279. self.inform.emit(
  6280. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6281. color='green', name=str(curr_sel_obj.options['name'])))
  6282. elif curr_sel_obj.kind == 'excellon':
  6283. self.inform.emit(
  6284. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6285. color='brown', name=str(curr_sel_obj.options['name'])))
  6286. elif curr_sel_obj.kind == 'cncjob':
  6287. self.inform.emit(
  6288. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6289. color='blue', name=str(curr_sel_obj.options['name'])))
  6290. elif curr_sel_obj.kind == 'geometry':
  6291. self.inform.emit(
  6292. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6293. color='red', name=str(curr_sel_obj.options['name'])))
  6294. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  6295. self.collection.set_all_inactive()
  6296. self.delete_selection_shape()
  6297. self.collection.set_active(objects_under_the_click_list[0])
  6298. # create the selection box around the selected object
  6299. curr_sel_obj = self.collection.get_active()
  6300. if self.defaults['global_selection_shape'] is True:
  6301. self.draw_selection_shape(curr_sel_obj)
  6302. # self.inform.emit('[selected] %s: %s selected' %
  6303. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6304. if curr_sel_obj.kind == 'gerber':
  6305. self.inform.emit(
  6306. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6307. color='green', name=str(curr_sel_obj.options['name'])))
  6308. elif curr_sel_obj.kind == 'excellon':
  6309. self.inform.emit(
  6310. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6311. color='brown', name=str(curr_sel_obj.options['name'])))
  6312. elif curr_sel_obj.kind == 'cncjob':
  6313. self.inform.emit(
  6314. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6315. color='blue', name=str(curr_sel_obj.options['name'])))
  6316. elif curr_sel_obj.kind == 'geometry':
  6317. self.inform.emit(
  6318. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6319. color='red', name=str(curr_sel_obj.options['name'])))
  6320. else:
  6321. self.collection.set_all_inactive()
  6322. self.delete_selection_shape()
  6323. if self.call_source == 'app':
  6324. # delete any text in the status bar, implicitly the last object name that was selected
  6325. self.inform.emit("")
  6326. else:
  6327. self.call_source = 'app'
  6328. else:
  6329. # If there is no selected object
  6330. # make active the first element of the overlapped objects list
  6331. if self.collection.get_active() is None:
  6332. self.collection.set_active(objects_under_the_click_list[0])
  6333. name_sel_obj = self.collection.get_active().options['name']
  6334. # In case that there is a selected object but it is not in the overlapped object list
  6335. # make that object inactive and activate the first element in the overlapped object list
  6336. if name_sel_obj not in objects_under_the_click_list:
  6337. self.collection.set_inactive(name_sel_obj)
  6338. name_sel_obj = objects_under_the_click_list[0]
  6339. self.collection.set_active(name_sel_obj)
  6340. else:
  6341. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  6342. self.collection.set_all_inactive()
  6343. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  6344. len(objects_under_the_click_list)])
  6345. curr_sel_obj = self.collection.get_active()
  6346. # delete the possible selection box around a possible selected object
  6347. self.delete_selection_shape()
  6348. # create the selection box around the selected object
  6349. if self.defaults['global_selection_shape'] is True:
  6350. self.draw_selection_shape(curr_sel_obj)
  6351. # self.inform.emit('[selected] %s: %s selected' %
  6352. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6353. if curr_sel_obj.kind == 'gerber':
  6354. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6355. color='green', name=str(curr_sel_obj.options['name'])))
  6356. elif curr_sel_obj.kind == 'excellon':
  6357. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6358. color='brown', name=str(curr_sel_obj.options['name'])))
  6359. elif curr_sel_obj.kind == 'cncjob':
  6360. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6361. color='blue', name=str(curr_sel_obj.options['name'])))
  6362. elif curr_sel_obj.kind == 'geometry':
  6363. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6364. color='red', name=str(curr_sel_obj.options['name'])))
  6365. # for obj in self.collection.get_list():
  6366. # obj.plot()
  6367. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  6368. # TODO: on selected objects change the object colors and do not draw the selection box
  6369. # self.plotcanvas.update() # this updates the canvas
  6370. except Exception as e:
  6371. log.error("[ERROR] Something went bad. %s" % str(e))
  6372. return
  6373. def delete_hover_shape(self):
  6374. self.hover_shapes.clear()
  6375. self.hover_shapes.redraw()
  6376. def draw_hover_shape(self, sel_obj, color=None):
  6377. """
  6378. :param sel_obj: the object for which the hover shape must be drawn
  6379. :return:
  6380. """
  6381. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6382. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6383. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6384. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6385. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  6386. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6387. hover_rect = hover_rect.buffer(-0.1)
  6388. hover_rect = hover_rect.buffer(0.2)
  6389. else:
  6390. hover_rect = hover_rect.buffer(-0.00393)
  6391. hover_rect = hover_rect.buffer(0.00787)
  6392. if color:
  6393. face = Color(color)
  6394. face.alpha = 0.2
  6395. outline = Color(color, alpha=0.8)
  6396. else:
  6397. face = Color(self.defaults['global_sel_fill'])
  6398. face.alpha = 0.2
  6399. outline = self.defaults['global_sel_line']
  6400. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  6401. def delete_selection_shape(self):
  6402. self.move_tool.sel_shapes.clear()
  6403. self.move_tool.sel_shapes.redraw()
  6404. def draw_selection_shape(self, sel_obj, color=None):
  6405. """
  6406. :param sel_obj: the object for which the selection shape must be drawn
  6407. :return:
  6408. """
  6409. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6410. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6411. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6412. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6413. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6414. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6415. sel_rect = sel_rect.buffer(-0.1)
  6416. sel_rect = sel_rect.buffer(0.2)
  6417. else:
  6418. sel_rect = sel_rect.buffer(-0.00393)
  6419. sel_rect = sel_rect.buffer(0.00787)
  6420. if color:
  6421. face = Color(color, alpha=0.2)
  6422. outline = Color(color, alpha=0.8)
  6423. else:
  6424. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  6425. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  6426. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  6427. color=outline,
  6428. face_color=face,
  6429. update=True,
  6430. layer=0,
  6431. tolerance=None))
  6432. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  6433. """
  6434. :param old_coords: old coordinates
  6435. :param coords: new coordinates
  6436. :return:
  6437. """
  6438. if 'color' in kwargs:
  6439. color = kwargs['color']
  6440. else:
  6441. color = self.defaults['global_sel_line']
  6442. if 'face_color' in kwargs:
  6443. face_color = kwargs['face_color']
  6444. else:
  6445. face_color = self.defaults['global_sel_fill']
  6446. if 'face_alpha' in kwargs:
  6447. face_alpha = kwargs['face_alpha']
  6448. else:
  6449. face_alpha = 0.3
  6450. x0, y0 = old_coords
  6451. x1, y1 = coords
  6452. pt1 = (x0, y0)
  6453. pt2 = (x1, y0)
  6454. pt3 = (x1, y1)
  6455. pt4 = (x0, y1)
  6456. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6457. color_t = Color(face_color)
  6458. color_t.alpha = face_alpha
  6459. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  6460. layer=0, tolerance=None)
  6461. def on_file_new_click(self):
  6462. if self.collection.get_list() and self.should_we_save:
  6463. msgbox = QtWidgets.QMessageBox()
  6464. # msgbox.setText("<B>Save changes ...</B>")
  6465. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6466. "Creating a New project will delete them.\n"
  6467. "Do you want to Save the project?"))
  6468. msgbox.setWindowTitle(_("Save changes"))
  6469. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6470. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6471. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6472. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6473. msgbox.setDefaultButton(bt_yes)
  6474. msgbox.exec_()
  6475. response = msgbox.clickedButton()
  6476. if response == bt_yes:
  6477. self.on_file_saveprojectas()
  6478. elif response == bt_cancel:
  6479. return
  6480. elif response == bt_no:
  6481. self.on_file_new()
  6482. else:
  6483. self.on_file_new()
  6484. self.inform.emit('[success] %s...' %
  6485. _("New Project created"))
  6486. def on_file_new(self, cli=None):
  6487. """
  6488. Callback for menu item File->New. Returns the application to its
  6489. startup state. This method is thread-safe.
  6490. :return: None
  6491. """
  6492. self.report_usage("on_file_new")
  6493. # Remove everything from memory
  6494. App.log.debug("on_file_new()")
  6495. if self.call_source != 'app':
  6496. self.editor2object(cleanup=True)
  6497. # ## EDITOR section
  6498. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  6499. self.exc_editor = FlatCAMExcEditor(self)
  6500. self.grb_editor = FlatCAMGrbEditor(self)
  6501. # Clear pool
  6502. self.clear_pool()
  6503. for obj in self.collection.get_list():
  6504. # delete shapes left drawn from mark shape_collections, if any
  6505. if isinstance(obj, FlatCAMGerber):
  6506. try:
  6507. obj.mark_shapes.enabled = False
  6508. obj.mark_shapes.clear(update=True)
  6509. except AttributeError:
  6510. pass
  6511. # also delete annotation shapes, if any
  6512. elif isinstance(obj, FlatCAMCNCjob):
  6513. try:
  6514. obj.annotation.enabled = False
  6515. obj.annotation.clear(update=True)
  6516. except AttributeError:
  6517. pass
  6518. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6519. self.init_tcl()
  6520. self.delete_selection_shape()
  6521. self.collection.delete_all()
  6522. self.setup_component_editor()
  6523. # Clear project filename
  6524. self.project_filename = None
  6525. # Load the application defaults
  6526. self.load_defaults(filename='current_defaults')
  6527. # Re-fresh project options
  6528. self.on_options_app2project()
  6529. # Init Tools
  6530. self.init_tools()
  6531. if cli is None:
  6532. # Close any Tabs opened in the Plot Tab Area section
  6533. for index in range(self.ui.plot_tab_area.count()):
  6534. self.ui.plot_tab_area.closeTab(index)
  6535. # for whatever reason previous command does not close the last tab so I do it manually
  6536. self.ui.plot_tab_area.closeTab(0)
  6537. # # And then add again the Plot Area
  6538. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  6539. self.ui.plot_tab_area.protectTab(0)
  6540. # take the focus of the Notebook on Project Tab.
  6541. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6542. self.set_ui_title(name=_("New Project - Not saved"))
  6543. def obj_properties(self):
  6544. self.report_usage("obj_properties()")
  6545. self.properties_tool.run(toggle=False)
  6546. def on_project_context_save(self):
  6547. obj = self.collection.get_active()
  6548. if type(obj) == FlatCAMGeometry:
  6549. self.on_file_exportdxf()
  6550. elif type(obj) == FlatCAMExcellon:
  6551. self.on_file_saveexcellon()
  6552. elif type(obj) == FlatCAMCNCjob:
  6553. obj.on_exportgcode_button_click()
  6554. elif type(obj) == FlatCAMGerber:
  6555. self.on_file_savegerber()
  6556. def obj_move(self):
  6557. self.report_usage("obj_move()")
  6558. self.move_tool.run(toggle=False)
  6559. def on_fileopengerber(self, checked=None, name=None):
  6560. """
  6561. File menu callback for opening a Gerber.
  6562. :return: None
  6563. """
  6564. self.report_usage("on_fileopengerber")
  6565. App.log.debug("on_fileopengerber()")
  6566. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6567. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6568. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  6569. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6570. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6571. "*.mil);;" \
  6572. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6573. "Allegro Files (*.art);;" \
  6574. "Mentor Files (*.pho *.gdo);;" \
  6575. "All Files (*.*)"
  6576. if name is None:
  6577. try:
  6578. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6579. directory=self.get_last_folder(),
  6580. filter=_filter_)
  6581. except TypeError:
  6582. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6583. filenames = [str(filename) for filename in filenames]
  6584. else:
  6585. filenames = [name]
  6586. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6587. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6588. _("Opening Gerber file.")),
  6589. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6590. color=QtGui.QColor("gray"))
  6591. if len(filenames) == 0:
  6592. self.inform.emit('[WARNING_NOTCL] %s' %
  6593. _("Open Gerber cancelled."))
  6594. else:
  6595. for filename in filenames:
  6596. if filename != '':
  6597. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6598. def on_fileopenexcellon(self, checked=None, name=None):
  6599. """
  6600. File menu callback for opening an Excellon file.
  6601. :return: None
  6602. """
  6603. self.report_usage("on_fileopenexcellon")
  6604. App.log.debug("on_fileopenexcellon()")
  6605. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6606. "All Files (*.*)"
  6607. if name is None:
  6608. try:
  6609. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6610. directory=self.get_last_folder(),
  6611. filter=_filter_)
  6612. except TypeError:
  6613. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6614. filenames = [str(filename) for filename in filenames]
  6615. else:
  6616. filenames = [str(name)]
  6617. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6618. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6619. _("Opening Excellon file.")),
  6620. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6621. color=QtGui.QColor("gray"))
  6622. if len(filenames) == 0:
  6623. self.inform.emit('[WARNING_NOTCL]%s' %
  6624. _(" Open Excellon cancelled."))
  6625. else:
  6626. for filename in filenames:
  6627. if filename != '':
  6628. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6629. def on_fileopengcode(self, checked=None, name=None):
  6630. """
  6631. File menu call back for opening gcode.
  6632. :return: None
  6633. """
  6634. self.report_usage("on_fileopengcode")
  6635. App.log.debug("on_fileopengcode()")
  6636. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6637. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6638. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  6639. "All Files (*.*)"
  6640. if name is None:
  6641. try:
  6642. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6643. directory=self.get_last_folder(),
  6644. filter=_filter_)
  6645. except TypeError:
  6646. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6647. filenames = [str(filename) for filename in filenames]
  6648. else:
  6649. filenames = [name]
  6650. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6651. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6652. _("Opening G-Code file.")),
  6653. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6654. color=QtGui.QColor("gray"))
  6655. if len(filenames) == 0:
  6656. self.inform.emit('[WARNING_NOTCL] %s' %
  6657. _("Open G-Code cancelled."))
  6658. else:
  6659. for filename in filenames:
  6660. if filename != '':
  6661. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename]})
  6662. def on_file_openproject(self, checked=None):
  6663. """
  6664. File menu callback for opening a project.
  6665. :return: None
  6666. """
  6667. self.report_usage("on_file_openproject")
  6668. App.log.debug("on_file_openproject()")
  6669. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6670. try:
  6671. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6672. directory=self.get_last_folder(), filter=_filter_)
  6673. except TypeError:
  6674. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6675. # The Qt methods above will return a QString which can cause problems later.
  6676. # So far json.dump() will fail to serialize it.
  6677. # TODO: Improve the serialization methods and remove this fix.
  6678. filename = str(filename)
  6679. if filename == "":
  6680. self.inform.emit('[WARNING_NOTCL] %s' %
  6681. _("Open Project cancelled."))
  6682. else:
  6683. # self.worker_task.emit({'fcn': self.open_project,
  6684. # 'params': [filename]})
  6685. # The above was failing because open_project() is not
  6686. # thread safe. The new_project()
  6687. self.open_project(filename)
  6688. def on_file_openconfig(self, checked=None):
  6689. """
  6690. File menu callback for opening a config file.
  6691. :return: None
  6692. """
  6693. self.report_usage("on_file_openconfig")
  6694. App.log.debug("on_file_openconfig()")
  6695. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6696. try:
  6697. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6698. directory=self.data_path, filter=_filter_)
  6699. except TypeError:
  6700. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6701. filter=_filter_)
  6702. if filename == "":
  6703. self.inform.emit('[WARNING_NOTCL] %s' %
  6704. _("Open Config cancelled."))
  6705. else:
  6706. self.open_config_file(filename)
  6707. def on_file_exportsvg(self):
  6708. """
  6709. Callback for menu item File->Export SVG.
  6710. :return: None
  6711. """
  6712. self.report_usage("on_file_exportsvg")
  6713. App.log.debug("on_file_exportsvg()")
  6714. obj = self.collection.get_active()
  6715. if obj is None:
  6716. self.inform.emit('[WARNING_NOTCL] %s' %
  6717. _("No object selected."))
  6718. msg = _("Please Select a Geometry object to export")
  6719. msgbox = QtWidgets.QMessageBox()
  6720. msgbox.setInformativeText(msg)
  6721. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6722. msgbox.setDefaultButton(bt_ok)
  6723. msgbox.exec_()
  6724. return
  6725. # Check for more compatible types and add as required
  6726. if (not isinstance(obj, FlatCAMGeometry)
  6727. and not isinstance(obj, FlatCAMGerber)
  6728. and not isinstance(obj, FlatCAMCNCjob)
  6729. and not isinstance(obj, FlatCAMExcellon)):
  6730. msg = '[ERROR_NOTCL] %s' % \
  6731. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6732. msgbox = QtWidgets.QMessageBox()
  6733. msgbox.setInformativeText(msg)
  6734. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6735. msgbox.setDefaultButton(bt_ok)
  6736. msgbox.exec_()
  6737. return
  6738. name = obj.options["name"]
  6739. _filter = "SVG File (*.svg);;All Files (*.*)"
  6740. try:
  6741. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6742. caption=_("Export SVG"),
  6743. directory=self.get_last_save_folder() + '/' + str(name),
  6744. filter=_filter)
  6745. except TypeError:
  6746. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  6747. filename = str(filename)
  6748. if filename == "":
  6749. self.inform.emit('[WARNING_NOTCL]%s' %
  6750. _(" Export SVG cancelled."))
  6751. return
  6752. else:
  6753. self.export_svg(name, filename)
  6754. if self.defaults["global_open_style"] is False:
  6755. self.file_opened.emit("SVG", filename)
  6756. self.file_saved.emit("SVG", filename)
  6757. def on_file_exportpng(self):
  6758. self.report_usage("on_file_exportpng")
  6759. App.log.debug("on_file_exportpng()")
  6760. self.date = str(datetime.today()).rpartition('.')[0]
  6761. self.date = ''.join(c for c in self.date if c not in ':-')
  6762. self.date = self.date.replace(' ', '_')
  6763. image = _screenshot()
  6764. data = np.asarray(image)
  6765. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6766. self.inform.emit('[[WARNING_NOTCL]] %s' %
  6767. _('Data must be a 3D array with last dimension 3 or 4'))
  6768. return
  6769. filter_ = "PNG File (*.png);;All Files (*.*)"
  6770. try:
  6771. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6772. caption=_("Export PNG Image"),
  6773. directory=self.get_last_save_folder() + '/png_' + self.date,
  6774. filter=filter_)
  6775. except TypeError:
  6776. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  6777. filename = str(filename)
  6778. if filename == "":
  6779. self.inform.emit(_("Export PNG cancelled."))
  6780. return
  6781. else:
  6782. write_png(filename, data)
  6783. if self.defaults["global_open_style"] is False:
  6784. self.file_opened.emit("png", filename)
  6785. self.file_saved.emit("png", filename)
  6786. def on_file_savegerber(self):
  6787. """
  6788. Callback for menu item in Project context menu.
  6789. :return: None
  6790. """
  6791. self.report_usage("on_file_savegerber")
  6792. App.log.debug("on_file_savegerber()")
  6793. obj = self.collection.get_active()
  6794. if obj is None:
  6795. self.inform.emit('[WARNING_NOTCL] %s' %
  6796. _("No object selected. Please select an Gerber object to export."))
  6797. return
  6798. # Check for more compatible types and add as required
  6799. if not isinstance(obj, FlatCAMGerber):
  6800. self.inform.emit('[ERROR_NOTCL] %s' %
  6801. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6802. return
  6803. name = self.collection.get_active().options["name"]
  6804. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6805. try:
  6806. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6807. caption="Save Gerber source file",
  6808. directory=self.get_last_save_folder() + '/' + name,
  6809. filter=_filter)
  6810. except TypeError:
  6811. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  6812. filename = str(filename)
  6813. if filename == "":
  6814. self.inform.emit('[WARNING_NOTCL] %s' %
  6815. _("Save Gerber source file cancelled."))
  6816. return
  6817. else:
  6818. self.save_source_file(name, filename)
  6819. if self.defaults["global_open_style"] is False:
  6820. self.file_opened.emit("Gerber", filename)
  6821. self.file_saved.emit("Gerber", filename)
  6822. def on_file_saveexcellon(self):
  6823. """
  6824. Callback for menu item in project context menu.
  6825. :return: None
  6826. """
  6827. self.report_usage("on_file_saveexcellon")
  6828. App.log.debug("on_file_saveexcellon()")
  6829. obj = self.collection.get_active()
  6830. if obj is None:
  6831. self.inform.emit('[WARNING_NOTCL] %s' %
  6832. _("No object selected. Please select an Excellon object to export."))
  6833. return
  6834. # Check for more compatible types and add as required
  6835. if not isinstance(obj, FlatCAMExcellon):
  6836. self.inform.emit('[ERROR_NOTCL] %s' %
  6837. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6838. return
  6839. name = self.collection.get_active().options["name"]
  6840. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6841. try:
  6842. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6843. caption=_("Save Excellon source file"),
  6844. directory=self.get_last_save_folder() + '/' + name,
  6845. filter=_filter)
  6846. except TypeError:
  6847. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  6848. filename = str(filename)
  6849. if filename == "":
  6850. self.inform.emit('[WARNING_NOTCL] %s' %
  6851. _("Saving Excellon source file cancelled."))
  6852. return
  6853. else:
  6854. self.save_source_file(name, filename)
  6855. if self.defaults["global_open_style"] is False:
  6856. self.file_opened.emit("Excellon", filename)
  6857. self.file_saved.emit("Excellon", filename)
  6858. def on_file_exportexcellon(self):
  6859. """
  6860. Callback for menu item File->Export->Excellon.
  6861. :return: None
  6862. """
  6863. self.report_usage("on_file_exportexcellon")
  6864. App.log.debug("on_file_exportexcellon()")
  6865. obj = self.collection.get_active()
  6866. if obj is None:
  6867. self.inform.emit('[WARNING_NOTCL] %s' %
  6868. _("No object selected. Please Select an Excellon object to export."))
  6869. return
  6870. # Check for more compatible types and add as required
  6871. if not isinstance(obj, FlatCAMExcellon):
  6872. self.inform.emit('[ERROR_NOTCL] %s' %
  6873. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6874. return
  6875. name = self.collection.get_active().options["name"]
  6876. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6877. try:
  6878. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6879. caption=_("Export Excellon"),
  6880. directory=self.get_last_save_folder() + '/' + name,
  6881. filter=_filter)
  6882. except TypeError:
  6883. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  6884. filename = str(filename)
  6885. if filename == "":
  6886. self.inform.emit('[WARNING_NOTCL] %s' %
  6887. _("Export Excellon cancelled."))
  6888. return
  6889. else:
  6890. self.export_excellon(name, filename)
  6891. if self.defaults["global_open_style"] is False:
  6892. self.file_opened.emit("Excellon", filename)
  6893. self.file_saved.emit("Excellon", filename)
  6894. def on_file_exportgerber(self):
  6895. """
  6896. Callback for menu item File->Export->Gerber.
  6897. :return: None
  6898. """
  6899. self.report_usage("on_file_exportgerber")
  6900. App.log.debug("on_file_exportgerber()")
  6901. obj = self.collection.get_active()
  6902. if obj is None:
  6903. self.inform.emit('[WARNING_NOTCL] %s' %
  6904. _("No object selected. Please Select an Gerber object to export."))
  6905. return
  6906. # Check for more compatible types and add as required
  6907. if not isinstance(obj, FlatCAMGerber):
  6908. self.inform.emit('[ERROR_NOTCL] %s' %
  6909. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6910. return
  6911. name = self.collection.get_active().options["name"]
  6912. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  6913. try:
  6914. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6915. caption=_("Export Gerber"),
  6916. directory=self.get_last_save_folder() + '/' + name,
  6917. filter=_filter_)
  6918. except TypeError:
  6919. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  6920. filename = str(filename)
  6921. if filename == "":
  6922. self.inform.emit('[WARNING_NOTCL] %s' %
  6923. _("Export Gerber cancelled."))
  6924. return
  6925. else:
  6926. self.export_gerber(name, filename)
  6927. if self.defaults["global_open_style"] is False:
  6928. self.file_opened.emit("Gerber", filename)
  6929. self.file_saved.emit("Gerber", filename)
  6930. def on_file_exportdxf(self):
  6931. """
  6932. Callback for menu item File->Export DXF.
  6933. :return: None
  6934. """
  6935. self.report_usage("on_file_exportdxf")
  6936. App.log.debug("on_file_exportdxf()")
  6937. obj = self.collection.get_active()
  6938. if obj is None:
  6939. self.inform.emit('[WARNING_NOTCL] %s' %
  6940. _("No object selected."))
  6941. msg = _("Please Select a Geometry object to export")
  6942. msgbox = QtWidgets.QMessageBox()
  6943. msgbox.setInformativeText(msg)
  6944. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6945. msgbox.setDefaultButton(bt_ok)
  6946. msgbox.exec_()
  6947. return
  6948. # Check for more compatible types and add as required
  6949. if not isinstance(obj, FlatCAMGeometry):
  6950. msg = '[ERROR_NOTCL] %s' % \
  6951. _("Only Geometry objects can be used.")
  6952. msgbox = QtWidgets.QMessageBox()
  6953. msgbox.setInformativeText(msg)
  6954. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6955. msgbox.setDefaultButton(bt_ok)
  6956. msgbox.exec_()
  6957. return
  6958. name = self.collection.get_active().options["name"]
  6959. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  6960. try:
  6961. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6962. caption=_("Export DXF"),
  6963. directory=self.get_last_save_folder() + '/' + name,
  6964. filter=_filter_)
  6965. except TypeError:
  6966. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  6967. filter=_filter_)
  6968. filename = str(filename)
  6969. if filename == "":
  6970. self.inform.emit('[WARNING_NOTCL] %s' %
  6971. _("Export DXF cancelled."))
  6972. return
  6973. else:
  6974. self.export_dxf(name, filename)
  6975. if self.defaults["global_open_style"] is False:
  6976. self.file_opened.emit("DXF", filename)
  6977. self.file_saved.emit("DXF", filename)
  6978. def on_file_importsvg(self, type_of_obj):
  6979. """
  6980. Callback for menu item File->Import SVG.
  6981. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6982. :type type_of_obj: str
  6983. :return: None
  6984. """
  6985. self.report_usage("on_file_importsvg")
  6986. App.log.debug("on_file_importsvg()")
  6987. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  6988. try:
  6989. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6990. directory=self.get_last_folder(), filter=_filter_)
  6991. except TypeError:
  6992. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6993. filter=_filter_)
  6994. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  6995. type_of_obj = "geometry"
  6996. filenames = [str(filename) for filename in filenames]
  6997. if len(filenames) == 0:
  6998. self.inform.emit('[WARNING_NOTCL] %s' %
  6999. _("Open SVG cancelled."))
  7000. else:
  7001. for filename in filenames:
  7002. if filename != '':
  7003. self.worker_task.emit({'fcn': self.import_svg,
  7004. 'params': [filename, type_of_obj]})
  7005. def on_file_importdxf(self, type_of_obj):
  7006. """
  7007. Callback for menu item File->Import DXF.
  7008. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7009. :type type_of_obj: str
  7010. :return: None
  7011. """
  7012. self.report_usage("on_file_importdxf")
  7013. App.log.debug("on_file_importdxf()")
  7014. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7015. try:
  7016. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7017. directory=self.get_last_folder(),
  7018. filter=_filter_)
  7019. except TypeError:
  7020. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7021. filter=_filter_)
  7022. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7023. type_of_obj = "geometry"
  7024. filenames = [str(filename) for filename in filenames]
  7025. if len(filenames) == 0:
  7026. self.inform.emit('[WARNING_NOTCL] %s' %
  7027. _("Open DXF cancelled."))
  7028. else:
  7029. for filename in filenames:
  7030. if filename != '':
  7031. self.worker_task.emit({'fcn': self.import_dxf,
  7032. 'params': [filename, type_of_obj]})
  7033. # ###############################################################################################################
  7034. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  7035. # ###############################################################################################################
  7036. def init_code_editor(self, name):
  7037. # Signals section
  7038. # Disconnect the old signals
  7039. try:
  7040. self.ui.buttonOpen.clicked.disconnect()
  7041. except TypeError:
  7042. pass
  7043. try:
  7044. self.ui.buttonSave.clicked.disconnect()
  7045. except TypeError:
  7046. pass
  7047. # add the tab if it was closed
  7048. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, '%s' % name)
  7049. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  7050. # delete the absolute and relative position and messages in the infobar
  7051. self.ui.position_label.setText("")
  7052. self.ui.rel_position_label.setText("")
  7053. # first clear previous text in text editor (if any)
  7054. self.ui.code_editor.clear()
  7055. self.ui.code_editor.setReadOnly(False)
  7056. self.toggle_codeeditor = True
  7057. self.ui.code_editor.completer_enable = False
  7058. self.ui.buttonRun.hide()
  7059. # make sure to keep a reference to the code editor
  7060. self.reference_code_editor = self.ui.code_editor
  7061. # Switch plot_area to CNCJob tab
  7062. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  7063. def on_view_source(self):
  7064. self.inform.emit('%s' %
  7065. _("Viewing the source code of the selected object."))
  7066. self.proc_container.view.set_busy(_("Loading..."))
  7067. try:
  7068. obj = self.collection.get_active()
  7069. except Exception as e:
  7070. log.debug("App.on_view_source() --> %s" % str(e))
  7071. self.inform.emit('[WARNING_NOTCL] %s' %
  7072. _("Select an Gerber or Excellon file to view it's source file."))
  7073. return 'fail'
  7074. if obj.kind == 'gerber':
  7075. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  7076. elif obj.kind == 'excellon':
  7077. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  7078. elif obj.kind == 'cncjob':
  7079. "GCode Files (*.NC);;All Files (*.*)"
  7080. else:
  7081. flt = "All Files (*.*)"
  7082. self.init_code_editor(name=_("Source Editor"))
  7083. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  7084. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  7085. # then append the text from GCode to the text editor
  7086. if obj.kind == 'cncjob':
  7087. try:
  7088. file = obj.export_gcode(
  7089. preamble=self.defaults["cncjob_prepend"],
  7090. postamble=self.defaults["cncjob_append"],
  7091. to_file=True)
  7092. if file == 'fail':
  7093. return 'fail'
  7094. except AttributeError:
  7095. self.inform.emit('[WARNING_NOTCL] %s' %
  7096. _("There is no selected object for which to see it's source file code."))
  7097. return 'fail'
  7098. else:
  7099. try:
  7100. file = StringIO(obj.source_file)
  7101. except AttributeError:
  7102. self.inform.emit('[WARNING_NOTCL] %s' %
  7103. _("There is no selected object for which to see it's source file code."))
  7104. return 'fail'
  7105. self.ui.cncjob_frame.hide()
  7106. try:
  7107. for line in file:
  7108. QtWidgets.QApplication.processEvents()
  7109. proc_line = str(line).strip('\n')
  7110. self.ui.code_editor.append(proc_line)
  7111. except Exception as e:
  7112. log.debug('App.on_view_source() -->%s' % str(e))
  7113. self.inform.emit('[ERROR] %s: %s' %
  7114. (_('Failed to load the source code for the selected object'), str(e)))
  7115. return
  7116. self.handleTextChanged()
  7117. self.ui.cncjob_frame.show()
  7118. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7119. self.proc_container.view.set_idle()
  7120. # self.ui.show()
  7121. def on_toggle_code_editor(self):
  7122. self.report_usage("on_toggle_code_editor()")
  7123. if self.toggle_codeeditor is False:
  7124. self.init_code_editor(name=_("Code Editor"))
  7125. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  7126. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  7127. else:
  7128. for idx in range(self.ui.plot_tab_area.count()):
  7129. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  7130. self.ui.plot_tab_area.closeTab(idx)
  7131. break
  7132. self.toggle_codeeditor = False
  7133. def on_filenewscript(self):
  7134. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7135. self.init_code_editor(name=_("Script Editor"))
  7136. self.ui.code_editor.completer_enable = True
  7137. self.ui.code_editor.append(_(
  7138. "#\n"
  7139. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  7140. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  7141. "#\n\n"
  7142. "# FlatCAM commands list:\n"
  7143. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, ClearCopper,\n"
  7144. "# Cncjob, Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames,\n"
  7145. "# GetSys, ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillDrills,\n"
  7146. "# MillSlots, Mirror, New, NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"
  7147. "# Options, Paint, Panelize, Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,\n"
  7148. "# SubtractRectangle, Version, WriteGCode\n"
  7149. "#\n\n"
  7150. ))
  7151. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  7152. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  7153. self.ui.buttonRun.show()
  7154. try:
  7155. self.ui.buttonRun.clicked.disconnect(self.handleRunCode)
  7156. except TypeError:
  7157. pass
  7158. self.ui.buttonRun.clicked.connect(self.handleRunCode)
  7159. self.handleTextChanged()
  7160. self.ui.code_editor.show()
  7161. def on_fileopenscript(self):
  7162. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7163. try:
  7164. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  7165. directory=self.get_last_folder(), filter=_filter_)
  7166. except TypeError:
  7167. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  7168. # The Qt methods above will return a QString which can cause problems later.
  7169. # So far json.dump() will fail to serialize it.
  7170. # TODO: Improve the serialization methods and remove this fix.
  7171. filename = str(filename)
  7172. if filename == "":
  7173. self.inform.emit('[WARNING_NOTCL] %s' %
  7174. _("Open TCL script cancelled."))
  7175. else:
  7176. self.on_filenewscript()
  7177. try:
  7178. with open(filename, "r") as opened_script:
  7179. try:
  7180. for line in opened_script:
  7181. proc_line = str(line).strip('\n')
  7182. self.ui.code_editor.append(proc_line)
  7183. except Exception as e:
  7184. log.debug('App.on_fileopenscript() -->%s' % str(e))
  7185. self.inform.emit('[ERROR] %s %s' %
  7186. (_('App.on_fileopenscript() -->'), str(e)))
  7187. return
  7188. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7189. self.handleTextChanged()
  7190. # self.ui.show()
  7191. except Exception as e:
  7192. log.debug("App.on_fileopenscript() -> %s" % str(e))
  7193. def on_filerunscript(self, name=None):
  7194. """
  7195. File menu callback for loading and running a TCL script.
  7196. :return: None
  7197. """
  7198. self.report_usage("on_filerunscript")
  7199. App.log.debug("on_file_runscript()")
  7200. if name:
  7201. filename = name
  7202. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7203. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7204. _("Executing FlatCAMScript file.")),
  7205. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7206. color=QtGui.QColor("gray"))
  7207. else:
  7208. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7209. try:
  7210. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7211. directory=self.get_last_folder(), filter=_filter_)
  7212. except TypeError:
  7213. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7214. # The Qt methods above will return a QString which can cause problems later.
  7215. # So far json.dump() will fail to serialize it.
  7216. # TODO: Improve the serialization methods and remove this fix.
  7217. filename = str(filename)
  7218. if filename == "":
  7219. self.inform.emit('[WARNING_NOTCL] %s' %
  7220. _("Run TCL script cancelled."))
  7221. else:
  7222. try:
  7223. with open(filename, "r") as tcl_script:
  7224. cmd_line_shellfile_content = tcl_script.read()
  7225. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  7226. except Exception as e:
  7227. log.debug("App.on_filerunscript() -> %s" % str(e))
  7228. sys.exit(2)
  7229. def on_file_saveproject(self):
  7230. """
  7231. Callback for menu item File->Save Project. Saves the project to
  7232. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7233. if set to None. The project is saved by calling ``self.save_project()``.
  7234. :return: None
  7235. """
  7236. self.report_usage("on_file_saveproject")
  7237. if self.project_filename is None:
  7238. self.on_file_saveprojectas()
  7239. else:
  7240. self.worker_task.emit({'fcn': self.save_project,
  7241. 'params': [self.project_filename]})
  7242. if self.defaults["global_open_style"] is False:
  7243. self.file_opened.emit("project", self.project_filename)
  7244. self.file_saved.emit("project", self.project_filename)
  7245. self.set_ui_title(name=self.project_filename)
  7246. self.should_we_save = False
  7247. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7248. """
  7249. Callback for menu item File->Save Project As... Opens a file
  7250. chooser and saves the project to the given file via
  7251. ``self.save_project()``.
  7252. :param make_copy if to be create a copy of the project; boolean
  7253. :param use_thread: if to be run in a separate thread; boolean
  7254. :param quit_action: if to be followed by quiting the application; boolean
  7255. :return: None
  7256. """
  7257. self.report_usage("on_file_saveprojectas")
  7258. self.date = str(datetime.today()).rpartition('.')[0]
  7259. self.date = ''.join(c for c in self.date if c not in ':-')
  7260. self.date = self.date.replace(' ', '_')
  7261. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  7262. try:
  7263. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7264. caption=_("Save Project As ..."),
  7265. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  7266. filter=filter_)
  7267. except TypeError:
  7268. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  7269. filename = str(filename)
  7270. if filename == '':
  7271. self.inform.emit('[WARNING_NOTCL] %s' %
  7272. _("Save Project cancelled."))
  7273. return
  7274. try:
  7275. f = open(filename, 'r')
  7276. f.close()
  7277. except IOError:
  7278. pass
  7279. if use_thread is True:
  7280. self.worker_task.emit({'fcn': self.save_project,
  7281. 'params': [filename, quit_action]})
  7282. else:
  7283. self.save_project(filename, quit_action)
  7284. # self.save_project(filename)
  7285. if self.defaults["global_open_style"] is False:
  7286. self.file_opened.emit("project", filename)
  7287. self.file_saved.emit("project", filename)
  7288. if not make_copy:
  7289. self.project_filename = filename
  7290. self.set_ui_title(name=self.project_filename)
  7291. self.should_we_save = False
  7292. def export_svg(self, obj_name, filename, scale_factor=0.00):
  7293. """
  7294. Exports a Geometry Object to an SVG file.
  7295. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7296. :param filename: Path to the SVG file to save to.
  7297. :param scale_factor: factor by which to change/scale the thickness of the features
  7298. :return:
  7299. """
  7300. self.report_usage("export_svg()")
  7301. if filename is None:
  7302. filename = self.defaults["global_last_save_folder"]
  7303. self.log.debug("export_svg()")
  7304. try:
  7305. obj = self.collection.get_by_name(str(obj_name))
  7306. except:
  7307. # TODO: The return behavior has not been established... should raise exception?
  7308. return "Could not retrieve object: %s" % obj_name
  7309. with self.proc_container.new(_("Exporting SVG")) as proc:
  7310. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7311. # Determine bounding area for svg export
  7312. bounds = obj.bounds()
  7313. size = obj.size()
  7314. # Convert everything to strings for use in the xml doc
  7315. svgwidth = str(size[0])
  7316. svgheight = str(size[1])
  7317. minx = str(bounds[0])
  7318. miny = str(bounds[1] - size[1])
  7319. uom = obj.units.lower()
  7320. # Add a SVG Header and footer to the svg output from shapely
  7321. # The transform flips the Y Axis so that everything renders
  7322. # properly within svg apps such as inkscape
  7323. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7324. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7325. svg_header += 'width="' + svgwidth + uom + '" '
  7326. svg_header += 'height="' + svgheight + uom + '" '
  7327. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7328. svg_header += '<g transform="scale(1,-1)">'
  7329. svg_footer = '</g> </svg>'
  7330. svg_elem = svg_header + exported_svg + svg_footer
  7331. # Parse the xml through a xml parser just to add line feeds
  7332. # and to make it look more pretty for the output
  7333. svgcode = parse_xml_string(svg_elem)
  7334. try:
  7335. with open(filename, 'w') as fp:
  7336. fp.write(svgcode.toprettyxml())
  7337. except PermissionError:
  7338. self.inform.emit('[WARNING] %s' %
  7339. _("Permission denied, saving not possible.\n"
  7340. "Most likely another app is holding the file open and not accessible."))
  7341. return 'fail'
  7342. if self.defaults["global_open_style"] is False:
  7343. self.file_opened.emit("SVG", filename)
  7344. self.file_saved.emit("SVG", filename)
  7345. self.inform.emit('[success] %s: %s' %
  7346. (_("SVG file exported to"), filename))
  7347. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  7348. """
  7349. Exports a Geometry Object to an SVG file in negative.
  7350. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7351. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7352. :param filename: Path to the SVG file to save to.
  7353. :param boundary: thickness of a black border to surround all the features
  7354. :param scale_factor: factor by which to change/scale the thickness of the features
  7355. :param use_thread: if to be run in a separate thread; boolean
  7356. :return:
  7357. """
  7358. self.report_usage("export_negative()")
  7359. if filename is None:
  7360. filename = self.defaults["global_last_save_folder"]
  7361. self.log.debug("export_svg() negative")
  7362. try:
  7363. obj = self.collection.get_by_name(str(obj_name))
  7364. except:
  7365. # TODO: The return behavior has not been established... should raise exception?
  7366. return "Could not retrieve object: %s" % obj_name
  7367. try:
  7368. box = self.collection.get_by_name(str(box_name))
  7369. except:
  7370. # TODO: The return behavior has not been established... should raise exception?
  7371. return "Could not retrieve object: %s" % box_name
  7372. if box is None:
  7373. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7374. (_("No object Box. Using instead"), obj))
  7375. box = obj
  7376. def make_negative_film():
  7377. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7378. # Determine bounding area for svg export
  7379. bounds = box.bounds()
  7380. size = box.size()
  7381. uom = obj.units.lower()
  7382. # Convert everything to strings for use in the xml doc
  7383. svgwidth = str(size[0] + (2 * boundary))
  7384. svgheight = str(size[1] + (2 * boundary))
  7385. minx = str(bounds[0] - boundary)
  7386. miny = str(bounds[1] + boundary + size[1])
  7387. miny_rect = str(bounds[1] - boundary)
  7388. # Add a SVG Header and footer to the svg output from shapely
  7389. # The transform flips the Y Axis so that everything renders
  7390. # properly within svg apps such as inkscape
  7391. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7392. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7393. svg_header += 'width="' + svgwidth + uom + '" '
  7394. svg_header += 'height="' + svgheight + uom + '" '
  7395. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7396. svg_header += '>'
  7397. svg_header += '<g transform="scale(1,-1)">'
  7398. svg_footer = '</g> </svg>'
  7399. # Change the attributes of the exported SVG
  7400. # We don't need stroke-width - wrong, we do when we have lines with certain width
  7401. # We set opacity to maximum
  7402. # We set the color to WHITE
  7403. root = ET.fromstring(exported_svg)
  7404. for child in root:
  7405. child.set('fill', '#FFFFFF')
  7406. child.set('opacity', '1.0')
  7407. child.set('stroke', '#FFFFFF')
  7408. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  7409. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  7410. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  7411. first_svg_elem_tag = 'rect'
  7412. first_svg_elem_attribs = {
  7413. 'x': minx,
  7414. 'y': miny_rect,
  7415. 'width': svgwidth,
  7416. 'height': svgheight,
  7417. 'id': 'neg_rect',
  7418. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  7419. }
  7420. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  7421. exported_svg = ET.tostring(root)
  7422. svg_elem = svg_header + str(exported_svg) + svg_footer
  7423. # Parse the xml through a xml parser just to add line feeds
  7424. # and to make it look more pretty for the output
  7425. doc = parse_xml_string(svg_elem)
  7426. try:
  7427. with open(filename, 'w') as fp:
  7428. fp.write(doc.toprettyxml())
  7429. except PermissionError:
  7430. self.inform.emit('[WARNING] %s' %
  7431. _("Permission denied, saving not possible.\n"
  7432. "Most likely another app is holding the file open and not accessible."))
  7433. return 'fail'
  7434. if self.defaults["global_open_style"] is False:
  7435. self.file_opened.emit("SVG", filename)
  7436. self.file_saved.emit("SVG", filename)
  7437. self.inform.emit('[success] %s: %s' %
  7438. (_("SVG file exported to"), filename))
  7439. if use_thread is True:
  7440. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7441. def job_thread_film(app_obj):
  7442. try:
  7443. make_negative_film()
  7444. except Exception as e:
  7445. proc.done()
  7446. return
  7447. proc.done()
  7448. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7449. else:
  7450. make_negative_film()
  7451. def export_svg_positive(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  7452. """
  7453. Exports a Geometry Object to an SVG file in positive black.
  7454. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7455. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7456. :param filename: Path to the SVG file to save to.
  7457. :param scale_factor: factor by which to change/scale the thickness of the features
  7458. :param use_thread: if to be run in a separate thread; boolean
  7459. :return:
  7460. """
  7461. self.report_usage("export_svg_positive()")
  7462. if filename is None:
  7463. filename = self.defaults["global_last_save_folder"]
  7464. self.log.debug("export_svg() black")
  7465. try:
  7466. obj = self.collection.get_by_name(str(obj_name))
  7467. except:
  7468. # TODO: The return behavior has not been established... should raise exception?
  7469. return "Could not retrieve object: %s" % obj_name
  7470. try:
  7471. box = self.collection.get_by_name(str(box_name))
  7472. except:
  7473. # TODO: The return behavior has not been established... should raise exception?
  7474. return "Could not retrieve object: %s" % box_name
  7475. if box is None:
  7476. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7477. (_("No object Box. Using instead"), obj))
  7478. box = obj
  7479. def make_positive_film():
  7480. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7481. self.progress.emit(40)
  7482. # Change the attributes of the exported SVG
  7483. # We don't need stroke-width
  7484. # We set opacity to maximum
  7485. # We set the colour to WHITE
  7486. root = ET.fromstring(exported_svg)
  7487. for child in root:
  7488. child.set('fill', str(self.defaults['tools_film_color']))
  7489. child.set('opacity', '1.0')
  7490. child.set('stroke', str(self.defaults['tools_film_color']))
  7491. exported_svg = ET.tostring(root)
  7492. # Determine bounding area for svg export
  7493. bounds = box.bounds()
  7494. size = box.size()
  7495. # This contain the measure units
  7496. uom = obj.units.lower()
  7497. # Define a boundary around SVG of about 1.0mm (~39mils)
  7498. if uom in "mm":
  7499. boundary = 1.0
  7500. else:
  7501. boundary = 0.0393701
  7502. self.progress.emit(80)
  7503. # Convert everything to strings for use in the xml doc
  7504. svgwidth = str(size[0] + (2 * boundary))
  7505. svgheight = str(size[1] + (2 * boundary))
  7506. minx = str(bounds[0] - boundary)
  7507. miny = str(bounds[1] + boundary + size[1])
  7508. self.log.debug(minx)
  7509. self.log.debug(miny)
  7510. # Add a SVG Header and footer to the svg output from shapely
  7511. # The transform flips the Y Axis so that everything renders
  7512. # properly within svg apps such as inkscape
  7513. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7514. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7515. svg_header += 'width="' + svgwidth + uom + '" '
  7516. svg_header += 'height="' + svgheight + uom + '" '
  7517. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7518. svg_header += '>'
  7519. svg_header += '<g transform="scale(1,-1)">'
  7520. svg_footer = '</g> </svg>'
  7521. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  7522. self.progress.emit(90)
  7523. # Parse the xml through a xml parser just to add line feeds
  7524. # and to make it look more pretty for the output
  7525. doc = parse_xml_string(svg_elem)
  7526. try:
  7527. with open(filename, 'w') as fp:
  7528. fp.write(doc.toprettyxml())
  7529. except PermissionError:
  7530. self.inform.emit('[WARNING] %s' %
  7531. _("Permission denied, saving not possible.\n"
  7532. "Most likely another app is holding the file open and not accessible."))
  7533. return 'fail'
  7534. self.progress.emit(100)
  7535. if self.defaults["global_open_style"] is False:
  7536. self.file_opened.emit("SVG", filename)
  7537. self.file_saved.emit("SVG", filename)
  7538. self.inform.emit('[success] %s: %s' %
  7539. (_("SVG file exported to"), filename))
  7540. if use_thread is True:
  7541. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7542. def job_thread_film(app_obj):
  7543. try:
  7544. make_positive_film()
  7545. except Exception as e:
  7546. proc.done()
  7547. return
  7548. proc.done()
  7549. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7550. else:
  7551. make_positive_film()
  7552. def save_source_file(self, obj_name, filename, use_thread=True):
  7553. """
  7554. Exports a FlatCAM Object to an Gerber/Excellon file.
  7555. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7556. :param filename: Path to the Gerber file to save to.
  7557. :param use_thread: if to be run in a separate thread
  7558. :return:
  7559. """
  7560. self.report_usage("save source file()")
  7561. if filename is None:
  7562. filename = self.defaults["global_last_save_folder"]
  7563. self.log.debug("save source file()")
  7564. obj = self.collection.get_by_name(obj_name)
  7565. file_string = StringIO(obj.source_file)
  7566. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7567. try:
  7568. with open(filename, 'w') as file:
  7569. file.writelines('G04*\n')
  7570. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7571. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7572. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7573. file.writelines('G04 Created on : %s*\n' % time_string)
  7574. for line in file_string:
  7575. file.writelines(line)
  7576. except PermissionError:
  7577. self.inform.emit('[WARNING] %s' %
  7578. _("Permission denied, saving not possible.\n"
  7579. "Most likely another app is holding the file open and not accessible."))
  7580. return 'fail'
  7581. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7582. """
  7583. Exports a Excellon Object to an Excellon file.
  7584. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7585. :param filename: Path to the Excellon file to save to.
  7586. :param use_thread: if to be run in a separate thread
  7587. :return:
  7588. """
  7589. self.report_usage("export_excellon()")
  7590. if filename is None:
  7591. filename = self.defaults["global_last_save_folder"]
  7592. self.log.debug("export_excellon()")
  7593. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7594. self.defaults["excellon_exp_decimals"]
  7595. )
  7596. units = ''
  7597. if local_use is None:
  7598. try:
  7599. obj = self.collection.get_by_name(str(obj_name))
  7600. except:
  7601. # TODO: The return behavior has not been established... should raise exception?
  7602. return "Could not retrieve object: %s" % obj_name
  7603. else:
  7604. obj = local_use
  7605. # updated units
  7606. eunits = self.defaults["excellon_exp_units"]
  7607. ewhole = self.defaults["excellon_exp_integer"]
  7608. efract = self.defaults["excellon_exp_decimals"]
  7609. ezeros = self.defaults["excellon_exp_zeros"]
  7610. eformat = self.defaults["excellon_exp_format"]
  7611. slot_type = self.defaults["excellon_exp_slot_type"]
  7612. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7613. if fc_units == 'MM':
  7614. factor = 1 if eunits == 'METRIC' else 0.03937
  7615. else:
  7616. factor = 25.4 if eunits == 'METRIC' else 1
  7617. def make_excellon():
  7618. try:
  7619. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7620. header = 'M48\n'
  7621. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7622. (str(self.version), str(self.version_date))
  7623. header += ';Filename: %s' % str(obj_name) + '\n'
  7624. header += ';Created on : %s' % time_str + '\n'
  7625. if eformat == 'dec':
  7626. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7627. header += eunits + '\n'
  7628. for tool in obj.tools:
  7629. if eunits == 'METRIC':
  7630. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7631. tool=str(tool),
  7632. dec=2)
  7633. else:
  7634. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7635. tool=str(tool),
  7636. dec=4)
  7637. else:
  7638. if ezeros == 'LZ':
  7639. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7640. form='ndec', e_zeros='LZ', factor=factor,
  7641. slot_type=slot_type)
  7642. header += '%s,%s\n' % (eunits, 'LZ')
  7643. header += format_exc
  7644. for tool in obj.tools:
  7645. if eunits == 'METRIC':
  7646. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7647. tool=str(tool),
  7648. dec=2)
  7649. else:
  7650. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7651. tool=str(tool),
  7652. dec=4)
  7653. else:
  7654. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7655. form='ndec', e_zeros='TZ', factor=factor,
  7656. slot_type=slot_type)
  7657. header += '%s,%s\n' % (eunits, 'TZ')
  7658. header += format_exc
  7659. for tool in obj.tools:
  7660. if eunits == 'METRIC':
  7661. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7662. tool=str(tool),
  7663. dec=2)
  7664. else:
  7665. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7666. tool=str(tool),
  7667. dec=4)
  7668. header += '%\n'
  7669. footer = 'M30\n'
  7670. exported_excellon = header
  7671. exported_excellon += excellon_code
  7672. exported_excellon += footer
  7673. if local_use is None:
  7674. try:
  7675. with open(filename, 'w') as fp:
  7676. fp.write(exported_excellon)
  7677. except PermissionError:
  7678. self.inform.emit('[WARNING] %s' %
  7679. _("Permission denied, saving not possible.\n"
  7680. "Most likely another app is holding the file open and not accessible."))
  7681. return 'fail'
  7682. if self.defaults["global_open_style"] is False:
  7683. self.file_opened.emit("Excellon", filename)
  7684. self.file_saved.emit("Excellon", filename)
  7685. self.inform.emit('[success] %s: %s' %
  7686. (_("Excellon file exported to"), filename))
  7687. else:
  7688. return exported_excellon
  7689. except Exception as e:
  7690. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7691. return 'fail'
  7692. if use_thread is True:
  7693. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7694. def job_thread_exc(app_obj):
  7695. ret = make_excellon()
  7696. if ret == 'fail':
  7697. self.inform.emit('[ERROR_NOTCL] %s' %
  7698. _('Could not export Excellon file.'))
  7699. return
  7700. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7701. else:
  7702. ret = make_excellon()
  7703. if ret == 'fail':
  7704. self.inform.emit('[ERROR_NOTCL] %s' %
  7705. _('Could not export Excellon file.'))
  7706. return 'fail'
  7707. if local_use is not None:
  7708. return ret
  7709. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7710. """
  7711. Exports a Gerber Object to an Gerber file.
  7712. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7713. :param filename: Path to the Gerber file to save to.
  7714. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7715. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7716. :param use_thread: if to be run in a separate thread
  7717. :return:
  7718. """
  7719. self.report_usage("export_gerber()")
  7720. if filename is None:
  7721. filename = self.defaults["global_last_save_folder"]
  7722. self.log.debug("export_gerber()")
  7723. if local_use is None:
  7724. try:
  7725. obj = self.collection.get_by_name(str(obj_name))
  7726. except:
  7727. # TODO: The return behavior has not been established... should raise exception?
  7728. return "Could not retrieve object: %s" % obj_name
  7729. else:
  7730. obj = local_use
  7731. # updated units
  7732. gunits = self.defaults["gerber_exp_units"]
  7733. gwhole = self.defaults["gerber_exp_integer"]
  7734. gfract = self.defaults["gerber_exp_decimals"]
  7735. gzeros = self.defaults["gerber_exp_zeros"]
  7736. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7737. if fc_units == 'MM':
  7738. factor = 1 if gunits == 'MM' else 0.03937
  7739. else:
  7740. factor = 25.4 if gunits == 'MM' else 1
  7741. def make_gerber():
  7742. try:
  7743. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7744. header = 'G04*\n'
  7745. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7746. (str(self.version), str(self.version_date))
  7747. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7748. header += 'G04 Created on : %s*' % time_str + '\n'
  7749. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7750. header += "%MO{units}*%\n".format(units=gunits)
  7751. for apid in obj.apertures:
  7752. if obj.apertures[apid]['type'] == 'C':
  7753. header += "%ADD{apid}{type},{size}*%\n".format(
  7754. apid=str(apid),
  7755. type='C',
  7756. size=(factor * obj.apertures[apid]['size'])
  7757. )
  7758. elif obj.apertures[apid]['type'] == 'R':
  7759. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7760. apid=str(apid),
  7761. type='R',
  7762. width=(factor * obj.apertures[apid]['width']),
  7763. height=(factor * obj.apertures[apid]['height'])
  7764. )
  7765. elif obj.apertures[apid]['type'] == 'O':
  7766. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7767. apid=str(apid),
  7768. type='O',
  7769. width=(factor * obj.apertures[apid]['width']),
  7770. height=(factor * obj.apertures[apid]['height'])
  7771. )
  7772. header += '\n'
  7773. # obsolete units but some software may need it
  7774. if gunits == 'IN':
  7775. header += 'G70*\n'
  7776. else:
  7777. header += 'G71*\n'
  7778. # Absolute Mode
  7779. header += 'G90*\n'
  7780. header += 'G01*\n'
  7781. # positive polarity
  7782. header += '%LPD*%\n'
  7783. footer = 'M02*\n'
  7784. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7785. exported_gerber = header
  7786. exported_gerber += gerber_code
  7787. exported_gerber += footer
  7788. if local_use is None:
  7789. try:
  7790. with open(filename, 'w') as fp:
  7791. fp.write(exported_gerber)
  7792. except PermissionError:
  7793. self.inform.emit('[WARNING] %s' %
  7794. _("Permission denied, saving not possible.\n"
  7795. "Most likely another app is holding the file open and not accessible."))
  7796. return 'fail'
  7797. if self.defaults["global_open_style"] is False:
  7798. self.file_opened.emit("Gerber", filename)
  7799. self.file_saved.emit("Gerber", filename)
  7800. self.inform.emit('[success] %s: %s' %
  7801. (_("Gerber file exported to"), filename))
  7802. else:
  7803. return exported_gerber
  7804. except Exception as e:
  7805. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7806. return 'fail'
  7807. if use_thread is True:
  7808. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7809. def job_thread_grb(app_obj):
  7810. ret = make_gerber()
  7811. if ret == 'fail':
  7812. self.inform.emit('[ERROR_NOTCL] %s' %
  7813. _('Could not export Gerber file.'))
  7814. return
  7815. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7816. else:
  7817. ret = make_gerber()
  7818. if ret == 'fail':
  7819. self.inform.emit('[ERROR_NOTCL] %s' %
  7820. _('Could not export Gerber file.'))
  7821. return 'fail'
  7822. if local_use is not None:
  7823. return ret
  7824. def export_dxf(self, obj_name, filename, use_thread=True):
  7825. """
  7826. Exports a Geometry Object to an DXF file.
  7827. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7828. :param filename: Path to the DXF file to save to.
  7829. :param use_thread: if to be run in a separate thread
  7830. :return:
  7831. """
  7832. self.report_usage("export_dxf()")
  7833. if filename is None:
  7834. filename = self.defaults["global_last_save_folder"]
  7835. self.log.debug("export_dxf()")
  7836. format_exc = ''
  7837. units = ''
  7838. try:
  7839. obj = self.collection.get_by_name(str(obj_name))
  7840. except:
  7841. # TODO: The return behavior has not been established... should raise exception?
  7842. return "Could not retrieve object: %s" % obj_name
  7843. # updated units
  7844. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7845. if units == 'IN' or units == 'INCH':
  7846. units = 'INCH'
  7847. elif units == 'MM' or units == 'METIRC':
  7848. units ='METRIC'
  7849. def make_dxf():
  7850. try:
  7851. dxf_code = obj.export_dxf()
  7852. dxf_code.saveas(filename)
  7853. if self.defaults["global_open_style"] is False:
  7854. self.file_opened.emit("DXF", filename)
  7855. self.file_saved.emit("DXF", filename)
  7856. self.inform.emit('[success] %s: %s' %
  7857. (_("DXF file exported to"), filename))
  7858. except:
  7859. return 'fail'
  7860. if use_thread is True:
  7861. with self.proc_container.new(_("Exporting DXF")) as proc:
  7862. def job_thread_exc(app_obj):
  7863. ret = make_dxf()
  7864. if ret == 'fail':
  7865. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  7866. _('Could not export DXF file.'))
  7867. return
  7868. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7869. else:
  7870. ret = make_dxf()
  7871. if ret == 'fail':
  7872. self.inform.emit('[WARNING_NOTCL] %s' %
  7873. _('Could not export DXF file.'))
  7874. return
  7875. def import_svg(self, filename, geo_type='geometry', outname=None):
  7876. """
  7877. Adds a new Geometry Object to the projects and populates
  7878. it with shapes extracted from the SVG file.
  7879. :param filename: Path to the SVG file.
  7880. :param outname:
  7881. :return:
  7882. """
  7883. self.report_usage("import_svg()")
  7884. obj_type = ""
  7885. if geo_type is None or geo_type == "geometry":
  7886. obj_type = "geometry"
  7887. elif geo_type == "gerber":
  7888. obj_type = geo_type
  7889. else:
  7890. self.inform.emit('[ERROR_NOTCL] %s' %
  7891. _("Not supported type is picked as parameter. "
  7892. "Only Geometry and Gerber are supported"))
  7893. return
  7894. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7895. def obj_init(geo_obj, app_obj):
  7896. geo_obj.import_svg(filename, obj_type, units=units)
  7897. geo_obj.multigeo = False
  7898. with self.proc_container.new(_("Importing SVG")) as proc:
  7899. # Object name
  7900. name = outname or filename.split('/')[-1].split('\\')[-1]
  7901. self.new_object(obj_type, name, obj_init, autoselected=False)
  7902. self.progress.emit(20)
  7903. # Register recent file
  7904. self.file_opened.emit("svg", filename)
  7905. # GUI feedback
  7906. self.inform.emit('[success] %s: %s' %
  7907. (_("Opened"), filename))
  7908. self.progress.emit(100)
  7909. def import_dxf(self, filename, geo_type='geometry', outname=None):
  7910. """
  7911. Adds a new Geometry Object to the projects and populates
  7912. it with shapes extracted from the DXF file.
  7913. :param filename: Path to the DXF file.
  7914. :param outname:
  7915. :type putname: str
  7916. :return:
  7917. """
  7918. self.report_usage("import_dxf()")
  7919. obj_type = ""
  7920. if geo_type is None or geo_type == "geometry":
  7921. obj_type = "geometry"
  7922. elif geo_type == "gerber":
  7923. obj_type = geo_type
  7924. else:
  7925. self.inform.emit('[ERROR_NOTCL] %s' %
  7926. _("Not supported type is picked as parameter. "
  7927. "Only Geometry and Gerber are supported"))
  7928. return
  7929. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7930. def obj_init(geo_obj, app_obj):
  7931. geo_obj.import_dxf(filename, obj_type, units=units)
  7932. geo_obj.multigeo = False
  7933. with self.proc_container.new(_("Importing DXF")) as proc:
  7934. # Object name
  7935. name = outname or filename.split('/')[-1].split('\\')[-1]
  7936. self.new_object(obj_type, name, obj_init, autoselected=False)
  7937. self.progress.emit(20)
  7938. # Register recent file
  7939. self.file_opened.emit("dxf", filename)
  7940. # GUI feedback
  7941. self.inform.emit('[success] %s: %s' %
  7942. (_("Opened"), filename))
  7943. self.progress.emit(100)
  7944. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  7945. """
  7946. Adds a new Geometry Object to the projects and populates
  7947. it with shapes extracted from the SVG file.
  7948. :param filename: Path to the SVG file.
  7949. :param o_type: type of FlatCAM objeect
  7950. :param dpi: dot per inch
  7951. :param mode: black or color
  7952. :param mask: dictate the level of detail
  7953. :param outname: name for the resulting file
  7954. :return:
  7955. """
  7956. self.report_usage("import_image()")
  7957. if o_type is None or o_type == "geometry":
  7958. obj_type = "geometry"
  7959. elif o_type == "gerber":
  7960. obj_type = o_type
  7961. else:
  7962. self.inform.emit('[ERROR_NOTCL] %s' %
  7963. _("Not supported type is picked as parameter. "
  7964. "Only Geometry and Gerber are supported"))
  7965. return
  7966. def obj_init(geo_obj, app_obj):
  7967. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  7968. geo_obj.multigeo = False
  7969. with self.proc_container.new(_("Importing Image")) as proc:
  7970. # Object name
  7971. name = outname or filename.split('/')[-1].split('\\')[-1]
  7972. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  7973. self.new_object(obj_type, name, obj_init)
  7974. self.progress.emit(20)
  7975. # Register recent file
  7976. self.file_opened.emit("image", filename)
  7977. # GUI feedback
  7978. self.inform.emit('[success] %s: %s' %
  7979. (_("Opened"), filename))
  7980. self.progress.emit(100)
  7981. def open_gerber(self, filename, outname=None):
  7982. """
  7983. Opens a Gerber file, parses it and creates a new object for
  7984. it in the program. Thread-safe.
  7985. :param outname: Name of the resulting object. None causes the
  7986. name to be that of the file.
  7987. :param filename: Gerber file filename
  7988. :type filename: str
  7989. :param follow: If true, the parser will not create polygons, just lines
  7990. following the gerber path.
  7991. :type follow: bool
  7992. :return: None
  7993. """
  7994. # How the object should be initialized
  7995. def obj_init(gerber_obj, app_obj):
  7996. assert isinstance(gerber_obj, FlatCAMGerber), \
  7997. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  7998. # Opening the file happens here
  7999. self.progress.emit(30)
  8000. try:
  8001. gerber_obj.parse_file(filename)
  8002. except IOError:
  8003. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8004. (_("Failed to open file"), filename))
  8005. app_obj.progress.emit(0)
  8006. return "fail"
  8007. except ParseError as err:
  8008. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  8009. (_("Failed to parse file"), filename, str(err)))
  8010. app_obj.progress.emit(0)
  8011. self.log.error(str(err))
  8012. return "fail"
  8013. except Exception as e:
  8014. log.debug("App.open_gerber() --> %s" % str(e))
  8015. msg = '[ERROR] %s' % \
  8016. _("An internal error has occurred. See shell.\n")
  8017. msg += traceback.format_exc()
  8018. app_obj.inform.emit(msg)
  8019. return "fail"
  8020. if gerber_obj.is_empty():
  8021. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  8022. # self.collection.set_active(gerber_obj.options["name"])
  8023. # self.collection.delete_active()
  8024. self.inform.emit('[ERROR_NOTCL] %s' %
  8025. _("Object is not Gerber file or empty. Aborting object creation."))
  8026. return "fail"
  8027. # Further parsing
  8028. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  8029. App.log.debug("open_gerber()")
  8030. with self.proc_container.new(_("Opening Gerber")) as proc:
  8031. self.progress.emit(10)
  8032. # Object name
  8033. name = outname or filename.split('/')[-1].split('\\')[-1]
  8034. # # ## Object creation # ##
  8035. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  8036. if ret == 'fail':
  8037. self.inform.emit('[ERROR_NOTCL]%s' %
  8038. _(' Open Gerber failed. Probable not a Gerber file.'))
  8039. return
  8040. # Register recent file
  8041. self.file_opened.emit("gerber", filename)
  8042. self.progress.emit(100)
  8043. # GUI feedback
  8044. self.inform.emit('[success] %s: %s' %
  8045. (_("Opened"), filename))
  8046. def open_excellon(self, filename, outname=None, plot=True):
  8047. """
  8048. Opens an Excellon file, parses it and creates a new object for
  8049. it in the program. Thread-safe.
  8050. :param outname: Name of the resulting object. None causes the
  8051. name to be that of the file.
  8052. :param filename: Excellon file filename
  8053. :type filename: str
  8054. :return: None
  8055. """
  8056. App.log.debug("open_excellon()")
  8057. # How the object should be initialized
  8058. def obj_init(excellon_obj, app_obj):
  8059. # self.progress.emit(20)
  8060. try:
  8061. ret = excellon_obj.parse_file(filename=filename)
  8062. if ret == "fail":
  8063. log.debug("Excellon parsing failed.")
  8064. self.inform.emit('[ERROR_NOTCL] %s' %
  8065. _("This is not Excellon file."))
  8066. return "fail"
  8067. except IOError:
  8068. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8069. (_("Cannot open file"), filename))
  8070. log.debug("Could not open Excellon object.")
  8071. self.progress.emit(0) # TODO: self and app_bjj mixed
  8072. return "fail"
  8073. except:
  8074. msg = '[ERROR_NOTCL] %s' % \
  8075. _("An internal error has occurred. See shell.\n")
  8076. msg += traceback.format_exc()
  8077. app_obj.inform.emit(msg)
  8078. return "fail"
  8079. ret = excellon_obj.create_geometry()
  8080. if ret == 'fail':
  8081. log.debug("Could not create geometry for Excellon object.")
  8082. return "fail"
  8083. for tool in excellon_obj.tools:
  8084. if excellon_obj.tools[tool]['solid_geometry']:
  8085. return
  8086. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8087. (_("No geometry found in file"), filename))
  8088. return "fail"
  8089. with self.proc_container.new(_("Opening Excellon.")):
  8090. # Object name
  8091. name = outname or filename.split('/')[-1].split('\\')[-1]
  8092. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8093. if ret_val == 'fail':
  8094. self.inform.emit('[ERROR_NOTCL] %s' %
  8095. _('Open Excellon file failed. Probable not an Excellon file.'))
  8096. return
  8097. # Register recent file
  8098. self.file_opened.emit("excellon", filename)
  8099. # GUI feedback
  8100. self.inform.emit('[success] %s: %s' %
  8101. (_("Opened"), filename))
  8102. def open_gcode(self, filename, outname=None, plot=True):
  8103. """
  8104. Opens a G-gcode file, parses it and creates a new object for
  8105. it in the program. Thread-safe.
  8106. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8107. :param filename: G-code file filename
  8108. :type filename: str
  8109. :return: None
  8110. """
  8111. App.log.debug("open_gcode()")
  8112. # How the object should be initialized
  8113. def obj_init(job_obj, app_obj_):
  8114. """
  8115. :param job_obj: the resulting object
  8116. :type app_obj_: App
  8117. """
  8118. assert isinstance(app_obj_, App), \
  8119. "Initializer expected App, got %s" % type(app_obj_)
  8120. self.progress.emit(10)
  8121. try:
  8122. f = open(filename)
  8123. gcode = f.read()
  8124. f.close()
  8125. except IOError:
  8126. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  8127. (_("Failed to open"), filename))
  8128. self.progress.emit(0)
  8129. return "fail"
  8130. job_obj.gcode = gcode
  8131. self.progress.emit(20)
  8132. ret = job_obj.gcode_parse()
  8133. if ret == "fail":
  8134. self.inform.emit('[ERROR_NOTCL] %s' %
  8135. _("This is not GCODE"))
  8136. return "fail"
  8137. self.progress.emit(60)
  8138. job_obj.create_geometry()
  8139. with self.proc_container.new(_("Opening G-Code.")):
  8140. # Object name
  8141. name = outname or filename.split('/')[-1].split('\\')[-1]
  8142. # New object creation and file processing
  8143. ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8144. if ret == 'fail':
  8145. self.inform.emit('[ERROR_NOTCL] %s' %
  8146. _("Failed to create CNCJob Object. Probable not a GCode file.\n "
  8147. "Attempting to create a FlatCAM CNCJob Object from "
  8148. "G-Code file failed during processing"))
  8149. return "fail"
  8150. # Register recent file
  8151. self.file_opened.emit("cncjob", filename)
  8152. # GUI feedback
  8153. self.inform.emit('[success] %s: %s' %
  8154. (_("Opened"), filename))
  8155. self.progress.emit(100)
  8156. def open_config_file(self, filename, run_from_arg=None):
  8157. """
  8158. Loads a config file from the specified file.
  8159. :param filename: Name of the file from which to load.
  8160. :type filename: str
  8161. :return: None
  8162. """
  8163. App.log.debug("Opening config file: " + filename)
  8164. if run_from_arg:
  8165. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8166. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8167. _("Opening FlatCAM Config file.")),
  8168. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8169. color=QtGui.QColor("gray"))
  8170. # add the tab if it was closed
  8171. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  8172. # first clear previous text in text editor (if any)
  8173. self.ui.code_editor.clear()
  8174. # Switch plot_area to CNCJob tab
  8175. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  8176. try:
  8177. if filename:
  8178. f = QtCore.QFile(filename)
  8179. if f.open(QtCore.QIODevice.ReadOnly):
  8180. stream = QtCore.QTextStream(f)
  8181. gcode_edited = stream.readAll()
  8182. self.ui.code_editor.setPlainText(gcode_edited)
  8183. f.close()
  8184. except IOError:
  8185. App.log.error("Failed to open config file: %s" % filename)
  8186. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8187. (_("Failed to open config file"), filename))
  8188. return
  8189. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  8190. """
  8191. Loads a project from the specified file.
  8192. 1) Loads and parses file
  8193. 2) Registers the file as recently opened.
  8194. 3) Calls on_file_new()
  8195. 4) Updates options
  8196. 5) Calls new_object() with the object's from_dict() as init method.
  8197. 6) Calls plot_all() if plot=True
  8198. :param filename: Name of the file from which to load.
  8199. :type filename: str
  8200. :param run_from_arg: True if run for arguments
  8201. :param plot: If True plot all objects in the project
  8202. :param cli: run from command line
  8203. :return: None
  8204. """
  8205. App.log.debug("Opening project: " + filename)
  8206. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8207. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8208. if cli is None:
  8209. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8210. if run_from_arg:
  8211. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8212. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8213. _("Opening FlatCAM Project file.")),
  8214. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8215. color=QtGui.QColor("gray"))
  8216. # Open and parse an uncompressed Project file
  8217. try:
  8218. f = open(filename, 'r')
  8219. except IOError:
  8220. App.log.error("Failed to open project file: %s" % filename)
  8221. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8222. (_("Failed to open project file"), filename))
  8223. return
  8224. try:
  8225. d = json.load(f, object_hook=dict2obj)
  8226. except Exception as e:
  8227. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8228. (filename, str(e)))
  8229. f.close()
  8230. # Open and parse a compressed Project file
  8231. try:
  8232. with lzma.open(filename) as f:
  8233. file_content = f.read().decode('utf-8')
  8234. d = json.loads(file_content, object_hook=dict2obj)
  8235. except Exception as e:
  8236. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8237. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8238. (_("Failed to open project file"), filename))
  8239. return
  8240. # Clear the current project
  8241. # # NOT THREAD SAFE # ##
  8242. if run_from_arg is True:
  8243. pass
  8244. elif cli is True:
  8245. self.delete_selection_shape()
  8246. else:
  8247. self.on_file_new()
  8248. # Project options
  8249. self.options.update(d['options'])
  8250. self.project_filename = filename
  8251. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8252. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8253. if cli is None:
  8254. self.set_screen_units(self.options["units"])
  8255. # Re create objects
  8256. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8257. for obj in d['objs']:
  8258. def obj_init(obj_inst, app_inst):
  8259. obj_inst.from_dict(obj)
  8260. App.log.debug("Recreating from opened project an %s object: %s" %
  8261. (obj['kind'].capitalize(), obj['options']['name']))
  8262. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8263. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8264. if cli is None:
  8265. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8266. obj['kind'].upper(),
  8267. obj['options']['name']
  8268. )
  8269. )
  8270. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  8271. self.inform.emit('[success] %s: %s' %
  8272. (_("Project loaded from"), filename))
  8273. self.should_we_save = False
  8274. self.file_opened.emit("project", filename)
  8275. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8276. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8277. if cli is None:
  8278. self.set_ui_title(name=self.project_filename)
  8279. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8280. def propagate_defaults(self, silent=False):
  8281. """
  8282. This method is used to set default values in classes. It's
  8283. an alternative to project options but allows the use
  8284. of values invisible to the user.
  8285. :return: None
  8286. """
  8287. if silent is False:
  8288. self.log.debug("propagate_defaults()")
  8289. # Which objects to update the given parameters.
  8290. routes = {
  8291. "global_zdownrate": CNCjob,
  8292. "excellon_zeros": Excellon,
  8293. "excellon_format_upper_in": Excellon,
  8294. "excellon_format_lower_in": Excellon,
  8295. "excellon_format_upper_mm": Excellon,
  8296. "excellon_format_lower_mm": Excellon,
  8297. "excellon_units": Excellon,
  8298. "gerber_use_buffer_for_union": Gerber,
  8299. "geometry_multidepth": Geometry
  8300. }
  8301. for param in routes:
  8302. if param in routes[param].defaults:
  8303. try:
  8304. routes[param].defaults[param] = self.defaults[param]
  8305. if silent is False:
  8306. self.log.debug(" " + param + " OK")
  8307. except KeyError:
  8308. if silent is False:
  8309. self.log.debug(" ERROR: " + param + " not in defaults.")
  8310. else:
  8311. # Try extracting the name:
  8312. # classname_param here is param in the object
  8313. if param.find(routes[param].__name__.lower() + "_") == 0:
  8314. p = param[len(routes[param].__name__) + 1:]
  8315. if p in routes[param].defaults:
  8316. routes[param].defaults[p] = self.defaults[param]
  8317. if silent is False:
  8318. self.log.debug(" " + param + " OK!")
  8319. def restore_main_win_geom(self):
  8320. try:
  8321. self.ui.setGeometry(self.defaults["global_def_win_x"],
  8322. self.defaults["global_def_win_y"],
  8323. self.defaults["global_def_win_w"],
  8324. self.defaults["global_def_win_h"])
  8325. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  8326. except KeyError as e:
  8327. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  8328. def plot_all(self, zoom=True):
  8329. """
  8330. Re-generates all plots from all objects.
  8331. :return: None
  8332. """
  8333. self.log.debug("Plot_all()")
  8334. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8335. for obj in self.collection.get_list():
  8336. def worker_task(obj):
  8337. with self.proc_container.new("Plotting"):
  8338. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8339. if zoom:
  8340. self.object_plotted.emit(obj)
  8341. # Send to worker
  8342. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  8343. def register_folder(self, filename):
  8344. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8345. def register_save_folder(self, filename):
  8346. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8347. def set_progress_bar(self, percentage, text=""):
  8348. self.ui.progress_bar.setValue(int(percentage))
  8349. def setup_shell(self):
  8350. """
  8351. Creates shell functions. Runs once at startup.
  8352. :return: None
  8353. """
  8354. self.log.debug("setup_shell()")
  8355. def shelp(p=None):
  8356. if not p:
  8357. return _("Available commands:\n") + \
  8358. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  8359. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  8360. if p not in commands:
  8361. return "Unknown command: %s" % p
  8362. return commands[p]["help"]
  8363. # --- Migrated to new architecture ---
  8364. # def options(name):
  8365. # ops = self.collection.get_by_name(str(name)).options
  8366. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  8367. def h(*args):
  8368. """
  8369. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  8370. and standalone parameters into list.
  8371. """
  8372. kwa = {}
  8373. a = []
  8374. n = len(args)
  8375. name = None
  8376. for i in range(n):
  8377. match = re.search(r'^-([a-zA-Z].*)', args[i])
  8378. if match:
  8379. assert name is None
  8380. name = match.group(1)
  8381. continue
  8382. if name is None:
  8383. a.append(args[i])
  8384. else:
  8385. kwa[name] = args[i]
  8386. name = None
  8387. return a, kwa
  8388. @contextmanager
  8389. def wait_signal(signal, timeout=10000):
  8390. """
  8391. Block loop until signal emitted, timeout (ms) elapses
  8392. or unhandled exception happens in a thread.
  8393. :param timeout: time after which the loop is exited
  8394. :param signal: Signal to wait for.
  8395. """
  8396. loop = QtCore.QEventLoop()
  8397. # Normal termination
  8398. signal.connect(loop.quit)
  8399. # Termination by exception in thread
  8400. self.thread_exception.connect(loop.quit)
  8401. status = {'timed_out': False}
  8402. def report_quit():
  8403. status['timed_out'] = True
  8404. loop.quit()
  8405. yield
  8406. # Temporarily change how exceptions are managed.
  8407. oeh = sys.excepthook
  8408. ex = []
  8409. def except_hook(type_, value, traceback_):
  8410. ex.append(value)
  8411. oeh(type_, value, traceback_)
  8412. sys.excepthook = except_hook
  8413. # Terminate on timeout
  8414. if timeout is not None:
  8415. QtCore.QTimer.singleShot(timeout, report_quit)
  8416. # # ## Block ## ##
  8417. loop.exec_()
  8418. # Restore exception management
  8419. sys.excepthook = oeh
  8420. if ex:
  8421. self.raiseTclError(str(ex[0]))
  8422. if status['timed_out']:
  8423. raise Exception('Timed out!')
  8424. def make_docs():
  8425. output = ''
  8426. import collections
  8427. od = collections.OrderedDict(sorted(commands.items()))
  8428. for cmd_, val in od.items():
  8429. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  8430. t = val['help']
  8431. usage_i = t.find('>')
  8432. if usage_i < 0:
  8433. expl = t
  8434. output += expl + '\n\n'
  8435. continue
  8436. expl = t[:usage_i - 1]
  8437. output += expl + '\n\n'
  8438. end_usage_i = t[usage_i:].find('\n')
  8439. if end_usage_i < 0:
  8440. end_usage_i = len(t[usage_i:])
  8441. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  8442. else:
  8443. extras = t[usage_i+end_usage_i+1:]
  8444. parts = [s.strip() for s in extras.split('\n')]
  8445. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  8446. for p in parts:
  8447. output += ' ' + p + '\n\n'
  8448. return output
  8449. '''
  8450. Howto implement TCL shell commands:
  8451. All parameters passed to command should be possible to set as None and test it afterwards.
  8452. This is because we need to see error caused in tcl,
  8453. if None value as default parameter is not allowed TCL will return empty error.
  8454. Use:
  8455. def mycommand(name=None,...):
  8456. Test it like this:
  8457. if name is None:
  8458. self.raise_tcl_error('Argument name is missing.')
  8459. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  8460. otherwise we will miss it and processing will silently continue.
  8461. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  8462. which is catched in exec_command and displayed in TCL shell console with red background.
  8463. Error in console is displayed with TCL trace.
  8464. This behavior works only within main thread,
  8465. errors with promissed tasks can be catched and detected only with log.
  8466. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  8467. TCL shell.
  8468. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  8469. '''
  8470. commands = {
  8471. 'help': {
  8472. 'fcn': shelp,
  8473. 'help': _("Shows list of commands.")
  8474. },
  8475. }
  8476. # Import/overwrite tcl commands as objects of TclCommand descendants
  8477. # This modifies the variable 'commands'.
  8478. tclCommands.register_all_commands(self, commands)
  8479. # Add commands to the tcl interpreter
  8480. for cmd in commands:
  8481. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  8482. # Make the tcl puts function return instead of print to stdout
  8483. self.tcl.eval('''
  8484. rename puts original_puts
  8485. proc puts {args} {
  8486. if {[llength $args] == 1} {
  8487. return "[lindex $args 0]"
  8488. } else {
  8489. eval original_puts $args
  8490. }
  8491. }
  8492. ''')
  8493. def setup_recent_items(self):
  8494. # TODO: Move this to constructor
  8495. icons = {
  8496. "gerber": "share/flatcam_icon16.png",
  8497. "excellon": "share/drill16.png",
  8498. 'geometry': "share/geometry16.png",
  8499. "cncjob": "share/cnc16.png",
  8500. "project": "share/project16.png",
  8501. "svg": "share/geometry16.png",
  8502. "dxf": "share/dxf16.png",
  8503. "pdf": "share/pdf32.png",
  8504. "image": "share/image16.png"
  8505. }
  8506. openers = {
  8507. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8508. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8509. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8510. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8511. 'project': self.open_project,
  8512. 'svg': self.import_svg,
  8513. 'dxf': self.import_dxf,
  8514. 'image': self.import_image,
  8515. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8516. }
  8517. # Open recent file for files
  8518. try:
  8519. f = open(self.data_path + '/recent.json')
  8520. except IOError:
  8521. App.log.error("Failed to load recent item list.")
  8522. self.inform.emit('[ERROR_NOTCL] %s' %
  8523. _("Failed to load recent item list."))
  8524. return
  8525. try:
  8526. self.recent = json.load(f)
  8527. except json.scanner.JSONDecodeError:
  8528. App.log.error("Failed to parse recent item list.")
  8529. self.inform.emit('[ERROR_NOTCL] %s' %
  8530. _("Failed to parse recent item list."))
  8531. f.close()
  8532. return
  8533. f.close()
  8534. # Open recent file for projects
  8535. try:
  8536. fp = open(self.data_path + '/recent_projects.json')
  8537. except IOError:
  8538. App.log.error("Failed to load recent project item list.")
  8539. self.inform.emit('[ERROR_NOTCL] %s' %
  8540. _("Failed to load recent projects item list."))
  8541. return
  8542. try:
  8543. self.recent_projects = json.load(fp)
  8544. except json.scanner.JSONDecodeError:
  8545. App.log.error("Failed to parse recent project item list.")
  8546. self.inform.emit('[ERROR_NOTCL] %s' %
  8547. _("Failed to parse recent project item list."))
  8548. fp.close()
  8549. return
  8550. fp.close()
  8551. # Closure needed to create callbacks in a loop.
  8552. # Otherwise late binding occurs.
  8553. def make_callback(func, fname):
  8554. def opener():
  8555. func(fname)
  8556. return opener
  8557. def reset_recent_files():
  8558. # Reset menu
  8559. self.ui.recent.clear()
  8560. self.recent = []
  8561. try:
  8562. f = open(self.data_path + '/recent.json', 'w')
  8563. except IOError:
  8564. App.log.error("Failed to open recent items file for writing.")
  8565. return
  8566. json.dump(self.recent, f)
  8567. def reset_recent_projects():
  8568. # Reset menu
  8569. self.ui.recent_projects.clear()
  8570. self.recent_projects = []
  8571. try:
  8572. fp = open(self.data_path + '/recent_projects.json', 'w')
  8573. except IOError:
  8574. App.log.error("Failed to open recent projects items file for writing.")
  8575. return
  8576. json.dump(self.recent, fp)
  8577. # Reset menu
  8578. self.ui.recent.clear()
  8579. self.ui.recent_projects.clear()
  8580. # Create menu items for projects
  8581. for recent in self.recent_projects:
  8582. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8583. if recent['kind'] == 'project':
  8584. try:
  8585. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8586. # Attach callback
  8587. o = make_callback(openers[recent["kind"]], recent['filename'])
  8588. action.triggered.connect(o)
  8589. self.ui.recent_projects.addAction(action)
  8590. except KeyError:
  8591. App.log.error("Unsupported file type: %s" % recent["kind"])
  8592. # Last action in Recent Files menu is one that Clear the content
  8593. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8594. clear_action_proj.triggered.connect(reset_recent_projects)
  8595. self.ui.recent_projects.addSeparator()
  8596. self.ui.recent_projects.addAction(clear_action_proj)
  8597. # Create menu items for files
  8598. for recent in self.recent:
  8599. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8600. if recent['kind'] != 'project':
  8601. try:
  8602. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8603. # Attach callback
  8604. o = make_callback(openers[recent["kind"]], recent['filename'])
  8605. action.triggered.connect(o)
  8606. self.ui.recent.addAction(action)
  8607. except KeyError:
  8608. App.log.error("Unsupported file type: %s" % recent["kind"])
  8609. # Last action in Recent Files menu is one that Clear the content
  8610. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8611. clear_action.triggered.connect(reset_recent_files)
  8612. self.ui.recent.addSeparator()
  8613. self.ui.recent.addAction(clear_action)
  8614. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8615. # self.ui.menufilerecent.set_submenu(recent_menu)
  8616. # recent_menu.show_all()
  8617. # self.ui.recent.show()
  8618. self.log.debug("Recent items list has been populated.")
  8619. def setup_component_editor(self):
  8620. # label = QtWidgets.QLabel("Choose an item from Project")
  8621. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8622. sel_title = QtWidgets.QTextEdit(
  8623. _('<b>Shortcut Key List</b>'))
  8624. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8625. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8626. settings = QSettings("Open Source", "FlatCAM")
  8627. if settings.contains("notebook_font_size"):
  8628. fsize = settings.value('notebook_font_size', type=int)
  8629. else:
  8630. fsize = 12
  8631. tsize = fsize + int(fsize / 2)
  8632. # selected_text = (_('''
  8633. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  8634. #
  8635. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8636. # The normal flow when working in FlatCAM is the following:</span></p>
  8637. #
  8638. # <ol>
  8639. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  8640. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8641. # even dragging and dropping the files on the GUI.<br />
  8642. # <br />
  8643. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  8644. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8645. # &nbsp;</li>
  8646. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  8647. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8648. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8649. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8650. # <br />
  8651. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  8652. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8653. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8654. # it even if it was out of focus.<br />
  8655. # <br />
  8656. # You can change the parameters in this screen and the flow direction is like this:<br />
  8657. # <br />
  8658. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  8659. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8660. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8661. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8662. # </ol>
  8663. #
  8664. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8665. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8666. # <strong>F3</strong>.</span></p>
  8667. #
  8668. # ''').format(fsize=fsize, tsize=tsize))
  8669. selected_text = '''
  8670. <p><span style="font-size:{tsize}px"><strong>%s</strong></span></p>
  8671. <p><span style="font-size:{fsize}px"><strong>%s</strong>:<br />
  8672. %s:</span></p>
  8673. <ol>
  8674. <li><span style="font-size:{fsize}px">%s menu&#39;s, %s.<br />
  8675. <br />
  8676. %s &amp; %s.</span><br />
  8677. &nbsp;</li>
  8678. <li><span style="font-size:{fsize}px">%s <strong>%s</strong> (%s), <strong>%s</strong> %s it-s %s.<br />
  8679. <br />
  8680. %s <strong>%s</strong> %s <strong>%s</strong> %s.<br />
  8681. <br />
  8682. %s:<br />
  8683. <br />
  8684. <strong>%s</strong> -&gt; %s -&gt; %s -&gt;<strong> %s </strong> -&gt; %s -&gt; %s -&gt;<strong> %s
  8685. </strong>-&gt; %s <strong>%s)&nbsp;</strong>-&gt; %s</span></li>
  8686. </ol>
  8687. <p><span style="font-size:{fsize}px">%s <strong>%s -&gt; %s</strong>&nbsp;%s it&#39;s %s:
  8688. <strong>F3</strong>.</span></p>
  8689. ''' % (
  8690. _("Selected Tab - Choose an Item from Project Tab"), _("Details"),
  8691. _("The normal flow when working in FlatCAM is the following"),
  8692. _("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the"),
  8693. _("toolbars, key shortcuts or even dragging and dropping the files on the GUI"),
  8694. _("You can also load a FlatCAM project by double clicking on the project file, drag"),
  8695. _("drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app"),
  8696. _("Once an object is available in the Project Tab, by selecting it and then focusing on"),
  8697. _("SELECTED TAB"), _("more simpler is to double click the object name in the Project Tab"),
  8698. _("SELECTED TAB"), _("will be updated with the object properties according to"),
  8699. _("kind: Gerber, Excellon, Geometry or CNCJob object"),
  8700. _("If the selection of the object is done on the canvas by single click instead, and the"),
  8701. _("SELECTED TAB"),
  8702. _("is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, "
  8703. "double clicking on the object on the canvas will bring the"),
  8704. _("SELECTED TAB"), _("and populate it even if it was out of focus"),
  8705. _("You can change the parameters in this screen and the flow direction is like this"),
  8706. _("Gerber/Excellon Object"), _("Change Parameter"), _("Generate Geometry"), _("Geometry Object"),
  8707. _("Add tools (change param in Selected Tab)"), _("Generate CNCJob"), _("CNCJob Object"),
  8708. _("Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in"), _("SELECTED TAB"),
  8709. _("Save GCode"), _("A list of key shortcuts is available through an menu entry in"), _("Help"),
  8710. _("Shortcuts List"), _("or through"), _("own key shortcut"),
  8711. )
  8712. sel_title.setText(selected_text)
  8713. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8714. self.ui.selected_scroll_area.setWidget(sel_title)
  8715. def setup_obj_classes(self):
  8716. """
  8717. Sets up application specifics on the FlatCAMObj class.
  8718. :return: None
  8719. """
  8720. FlatCAMObj.app = self
  8721. ObjectCollection.app = self
  8722. Gerber.app = self
  8723. Excellon.app = self
  8724. Geometry.app = self
  8725. CNCjob.app = self
  8726. FCProcess.app = self
  8727. FCProcessContainer.app = self
  8728. def version_check(self):
  8729. """
  8730. Checks for the latest version of the program. Alerts the
  8731. user if theirs is outdated. This method is meant to be run
  8732. in a separate thread.
  8733. :return: None
  8734. """
  8735. self.log.debug("version_check()")
  8736. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8737. full_url = App.version_url + \
  8738. "?s=" + str(self.defaults['global_serial']) + \
  8739. "&v=" + str(self.version) + \
  8740. "&os=" + str(self.os) + \
  8741. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  8742. else:
  8743. # no_stats dict; just so it won't break things on website
  8744. no_ststs_dict = {}
  8745. no_ststs_dict["global_ststs"] = {}
  8746. full_url = App.version_url + \
  8747. "?s=" + str(self.defaults['global_serial']) + \
  8748. "&v=" + str(self.version) + \
  8749. "&os=" + str(self.os) + \
  8750. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8751. App.log.debug("Checking for updates @ %s" % full_url)
  8752. # ## Get the data
  8753. try:
  8754. f = urllib.request.urlopen(full_url)
  8755. except:
  8756. # App.log.warning("Failed checking for latest version. Could not connect.")
  8757. self.log.warning("Failed checking for latest version. Could not connect.")
  8758. self.inform.emit('[WARNING_NOTCL] %s' %
  8759. _("Failed checking for latest version. Could not connect."))
  8760. return
  8761. try:
  8762. data = json.load(f)
  8763. except Exception as e:
  8764. App.log.error("Could not parse information about latest version.")
  8765. self.inform.emit('[ERROR_NOTCL] %s' %
  8766. _("Could not parse information about latest version."))
  8767. App.log.debug("json.load(): %s" % str(e))
  8768. f.close()
  8769. return
  8770. f.close()
  8771. # ## Latest version?
  8772. if self.version >= data["version"]:
  8773. App.log.debug("FlatCAM is up to date!")
  8774. self.inform.emit('[success] %s' %
  8775. _("FlatCAM is up to date!"))
  8776. return
  8777. App.log.debug("Newer version available.")
  8778. self.message.emit(
  8779. _("Newer Version Available"),
  8780. _("There is a newer version of FlatCAM available for download:\n\n") +
  8781. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  8782. _("info")
  8783. )
  8784. def on_plotcanvas_setup(self, container=None):
  8785. """
  8786. This is doing the setup for the plot area (VisPy canvas)
  8787. :param container: widget where to install the canvas
  8788. :return: None
  8789. """
  8790. if container:
  8791. plot_container = container
  8792. else:
  8793. plot_container = self.ui.right_layout
  8794. self.plotcanvas = PlotCanvas(plot_container, self)
  8795. # So it can receive key presses
  8796. self.plotcanvas.native.setFocus()
  8797. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  8798. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  8799. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8800. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  8801. # Keys over plot enabled
  8802. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  8803. self.app_cursor = self.plotcanvas.new_cursor()
  8804. self.app_cursor.enabled = False
  8805. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8806. def on_zoom_fit(self, event):
  8807. """
  8808. Callback for zoom-out request. This can be either from the corresponding
  8809. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8810. with axes limits from the geometry bounds of all objects.
  8811. :param event: Ignored.
  8812. :return: None
  8813. """
  8814. self.plotcanvas.fit_view()
  8815. def on_zoom_in(self):
  8816. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8817. def on_zoom_out(self):
  8818. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8819. def disable_all_plots(self):
  8820. self.report_usage("disable_all_plots()")
  8821. self.disable_plots(self.collection.get_list())
  8822. self.inform.emit('[success] %s' %
  8823. _("All plots disabled."))
  8824. def disable_other_plots(self):
  8825. self.report_usage("disable_other_plots()")
  8826. self.disable_plots(self.collection.get_non_selected())
  8827. self.inform.emit('[success] %s' %
  8828. _("All non selected plots disabled."))
  8829. def enable_all_plots(self):
  8830. self.report_usage("enable_all_plots()")
  8831. self.enable_plots(self.collection.get_list())
  8832. self.inform.emit('[success] %s' %
  8833. _("All plots enabled."))
  8834. def on_enable_sel_plots(self):
  8835. log.debug("App.on_enable_sel_plot()")
  8836. object_list = self.collection.get_selected()
  8837. self.enable_plots(objects=object_list)
  8838. self.inform.emit('[success] %s' %
  8839. _("Selected plots enabled..."))
  8840. def on_disable_sel_plots(self):
  8841. log.debug("App.on_disable_sel_plot()")
  8842. # self.inform.emit(_("Disabling plots ..."))
  8843. object_list = self.collection.get_selected()
  8844. self.disable_plots(objects=object_list)
  8845. self.inform.emit('[success] %s' %
  8846. _("Selected plots disabled..."))
  8847. def enable_plots(self, objects):
  8848. """
  8849. Disables plots
  8850. :param objects: list of Objects to be enabled
  8851. :return:
  8852. """
  8853. log.debug("Enabling plots ...")
  8854. # self.inform.emit(_("Working ..."))
  8855. for obj in objects:
  8856. if obj.options['plot'] is False:
  8857. obj.options.set_change_callback(lambda x: None)
  8858. obj.options['plot'] = True
  8859. obj.options.set_change_callback(obj.on_options_change)
  8860. def worker_task(objects):
  8861. with self.proc_container.new(_("Enabling plots ...")):
  8862. for obj in objects:
  8863. # obj.options['plot'] = True
  8864. if isinstance(obj, FlatCAMCNCjob):
  8865. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8866. else:
  8867. obj.plot(visible=True)
  8868. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8869. # self.plots_updated.emit()
  8870. def disable_plots(self, objects):
  8871. """
  8872. Disables plots
  8873. :param objects: list of Objects to be disabled
  8874. :return:
  8875. """
  8876. # if no objects selected then do nothing
  8877. if not self.collection.get_selected():
  8878. return
  8879. log.debug("Disabling plots ...")
  8880. # self.inform.emit(_("Working ..."))
  8881. for obj in objects:
  8882. if obj.options['plot'] is True:
  8883. obj.options.set_change_callback(lambda x: None)
  8884. obj.options['plot'] = False
  8885. obj.options.set_change_callback(obj.on_options_change)
  8886. try:
  8887. self.delete_selection_shape()
  8888. except Exception as e:
  8889. log.debug("App.disable_plots() --> %s" % str(e))
  8890. # self.plots_updated.emit()
  8891. def worker_task(objects):
  8892. with self.proc_container.new(_("Disabling plots ...")):
  8893. for obj in objects:
  8894. # obj.options['plot'] = True
  8895. if isinstance(obj, FlatCAMCNCjob):
  8896. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8897. else:
  8898. obj.plot(visible=False)
  8899. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8900. def toggle_plots(self, objects):
  8901. """
  8902. Toggle plots visibility
  8903. :param objects: list of Objects for which to be toggled the visibility
  8904. :return:
  8905. """
  8906. # if no objects selected then do nothing
  8907. if not self.collection.get_selected():
  8908. return
  8909. log.debug("Toggling plots ...")
  8910. self.inform.emit(_("Working ..."))
  8911. for obj in objects:
  8912. if obj.options['plot'] is False:
  8913. obj.options['plot'] = True
  8914. else:
  8915. obj.options['plot'] = False
  8916. self.plots_updated.emit()
  8917. def clear_plots(self):
  8918. objects = self.collection.get_list()
  8919. for obj in objects:
  8920. obj.clear(obj == objects[-1])
  8921. # Clear pool to free memory
  8922. self.clear_pool()
  8923. def generate_cnc_job(self, objects):
  8924. self.report_usage("generate_cnc_job()")
  8925. # for obj in objects:
  8926. # obj.generatecncjob()
  8927. for obj in objects:
  8928. obj.on_generatecnc_button_click()
  8929. def save_project(self, filename, quit_action=False):
  8930. """
  8931. Saves the current project to the specified file.
  8932. :param filename: Name of the file in which to save.
  8933. :type filename: str
  8934. :param quit_action: if the project saving will be followed by an app quit; boolean
  8935. :return: None
  8936. """
  8937. self.log.debug("save_project()")
  8938. self.save_in_progress = True
  8939. with self.proc_container.new(_("Saving FlatCAM Project")) as proc:
  8940. # Capture the latest changes
  8941. # Current object
  8942. try:
  8943. self.collection.get_active().read_form()
  8944. except:
  8945. self.log.debug("There was no active object")
  8946. pass
  8947. # Project options
  8948. self.options_read_form()
  8949. # Serialize the whole project
  8950. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8951. "options": self.options,
  8952. "version": self.version}
  8953. if self.defaults["global_save_compressed"] is True:
  8954. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8955. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8956. # # Write
  8957. f.write(g)
  8958. self.inform.emit('[success] %s: %s' %
  8959. (_("Project saved to"), filename))
  8960. else:
  8961. # Open file
  8962. try:
  8963. f = open(filename, 'w')
  8964. except IOError:
  8965. App.log.error("Failed to open file for saving: %s", filename)
  8966. return
  8967. # Write
  8968. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8969. f.close()
  8970. # verification of the saved project
  8971. # Open and parse
  8972. try:
  8973. saved_f = open(filename, 'r')
  8974. except IOError:
  8975. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8976. (_("Failed to verify project file"), filename, _("Retry to save it."))
  8977. )
  8978. return
  8979. try:
  8980. saved_d = json.load(saved_f, object_hook=dict2obj)
  8981. except:
  8982. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8983. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  8984. )
  8985. f.close()
  8986. return
  8987. saved_f.close()
  8988. if 'version' in saved_d:
  8989. self.inform.emit('[success] %s: %s' %
  8990. (_("Project saved to"), filename))
  8991. else:
  8992. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8993. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  8994. )
  8995. settings = QSettings("Open Source", "FlatCAM")
  8996. lock_state = self.ui.lock_action.isChecked()
  8997. settings.setValue('toolbar_lock', lock_state)
  8998. # This will write the setting to the platform specific storage.
  8999. del settings
  9000. # if quit:
  9001. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  9002. # t.start()
  9003. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  9004. def start_delayed_quit(self, delay, filename, should_quit=None):
  9005. """
  9006. :param delay: period of checking if project file size is more than zero; in seconds
  9007. :param filename: the name of the project file to be checked periodically for size more than zero
  9008. :param should_quit: if the task finished will be followed by an app quit; boolean
  9009. :return:
  9010. """
  9011. to_quit = should_quit
  9012. self.save_timer = QtCore.QTimer()
  9013. self.save_timer.setInterval(delay)
  9014. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  9015. self.save_timer.start()
  9016. def check_project_file_size(self, filename, should_quit=None):
  9017. """
  9018. :param filename: the name of the project file to be checked periodically for size more than zero
  9019. :param should_quit: will quit the app if True; boolean
  9020. :return:
  9021. """
  9022. try:
  9023. if os.stat(filename).st_size > 0:
  9024. self.save_in_progress = False
  9025. self.save_timer.stop()
  9026. if should_quit:
  9027. self.app_quit.emit()
  9028. except Exception as e:
  9029. traceback.print_exc()
  9030. def on_options_app2project(self):
  9031. """
  9032. Callback for Options->Transfer Options->App=>Project. Copies options
  9033. from application defaults to project defaults.
  9034. :return: None
  9035. """
  9036. self.report_usage("on_options_app2project")
  9037. self.defaults_read_form()
  9038. self.options.update(self.defaults)
  9039. self.options_write_form()
  9040. def on_options_project2app(self):
  9041. """
  9042. Callback for Options->Transfer Options->Project=>App. Copies options
  9043. from project defaults to application defaults.
  9044. :return: None
  9045. """
  9046. self.report_usage("on_options_project2app")
  9047. self.options_read_form()
  9048. self.defaults.update(self.options)
  9049. self.defaults_write_form()
  9050. def on_options_project2object(self):
  9051. """
  9052. Callback for Options->Transfer Options->Project=>Object. Copies options
  9053. from project defaults to the currently selected object.
  9054. :return: None
  9055. """
  9056. self.report_usage("on_options_project2object")
  9057. self.options_read_form()
  9058. obj = self.collection.get_active()
  9059. if obj is None:
  9060. self.inform.emit('[WARNING_NOTCL] %s' %
  9061. _("No object selected."))
  9062. return
  9063. for option in self.options:
  9064. if option.find(obj.kind + "_") == 0:
  9065. oname = option[len(obj.kind) + 1:]
  9066. obj.options[oname] = self.options[option]
  9067. obj.to_form() # Update UI
  9068. def on_options_object2project(self):
  9069. """
  9070. Callback for Options->Transfer Options->Object=>Project. Copies options
  9071. from the currently selected object to project defaults.
  9072. :return: None
  9073. """
  9074. self.report_usage("on_options_object2project")
  9075. obj = self.collection.get_active()
  9076. if obj is None:
  9077. self.inform.emit('[WARNING_NOTCL] %s' %
  9078. _("No object selected."))
  9079. return
  9080. obj.read_form()
  9081. for option in obj.options:
  9082. if option in ['name']: # TODO: Handle this better...
  9083. continue
  9084. self.options[obj.kind + "_" + option] = obj.options[option]
  9085. self.options_write_form()
  9086. def on_options_object2app(self):
  9087. """
  9088. Callback for Options->Transfer Options->Object=>App. Copies options
  9089. from the currently selected object to application defaults.
  9090. :return: None
  9091. """
  9092. self.report_usage("on_options_object2app")
  9093. obj = self.collection.get_active()
  9094. if obj is None:
  9095. self.inform.emit('[WARNING_NOTCL] %s' %
  9096. _("No object selected."))
  9097. return
  9098. obj.read_form()
  9099. for option in obj.options:
  9100. if option in ['name']: # TODO: Handle this better...
  9101. continue
  9102. self.defaults[obj.kind + "_" + option] = obj.options[option]
  9103. self.defaults_write_form()
  9104. def on_options_app2object(self):
  9105. """
  9106. Callback for Options->Transfer Options->App=>Object. Copies options
  9107. from application defaults to the currently selected object.
  9108. :return: None
  9109. """
  9110. self.report_usage("on_options_app2object")
  9111. self.defaults_read_form()
  9112. obj = self.collection.get_active()
  9113. if obj is None:
  9114. self.inform.emit('[WARNING_NOTCL] %s' %
  9115. _("No object selected."))
  9116. return
  9117. for option in self.defaults:
  9118. if option.find(obj.kind + "_") == 0:
  9119. oname = option[len(obj.kind) + 1:]
  9120. obj.options[oname] = self.defaults[option]
  9121. obj.to_form() # Update UI
  9122. class ArgsThread(QtCore.QObject):
  9123. open_signal = pyqtSignal(list)
  9124. start = pyqtSignal()
  9125. if sys.platform == 'win32':
  9126. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  9127. else:
  9128. address = ('/tmp/testipc', 'AF_UNIX')
  9129. def __init__(self):
  9130. super(ArgsThread, self).__init__()
  9131. self.start.connect(self.run)
  9132. def my_loop(self, address):
  9133. try:
  9134. listener = Listener(*address)
  9135. while True:
  9136. conn = listener.accept()
  9137. self.serve(conn)
  9138. except socket.error as e:
  9139. conn = Client(*address)
  9140. conn.send(sys.argv)
  9141. conn.send('close')
  9142. # close the current instance only if there are args
  9143. if len(sys.argv) > 1:
  9144. sys.exit()
  9145. def serve(self, conn):
  9146. while True:
  9147. msg = conn.recv()
  9148. if msg == 'close':
  9149. break
  9150. self.open_signal.emit(msg)
  9151. conn.close()
  9152. # the decorator is a must; without it this technique will not work unless the start signal is connected
  9153. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  9154. @pyqtSlot()
  9155. def run(self):
  9156. self.my_loop(self.address)
  9157. class GracefulException(Exception):
  9158. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  9159. def __init__(self):
  9160. super().__init__()
  9161. def __str__(self):
  9162. return ('\n\n%s' % _("The user requested a graceful exit of the current task."))
  9163. # end of file